2016-08-12 41 views
0

项目源代码具有用于SQL处理的Java方法。该方法确实有效,但它使用了一个有问题的解决方法:try-catch在正常执行的方法的最后部分阻塞。什么是实施它的正确方法?在该方法中尝试捕获//这是一种解决方法。它应该如何重新修复?

public void run() { 
     if (running) { 
      return; 
     } 
     running = true;    
     while(null == Common.server || null == Common.database || !ConnectionsPool.isInitialized()) { 
      // Wait until the database is set before continuing... 
      try { 
       Thread.sleep(1000); 
      } 
      catch(Exception ex) {} 
     } 
     while(running) { 
      final Connections cs = ConnectionsPool.getConnections(); 
      Connection c = null; 
      while(!entries.isEmpty()) { 
       if (null == c) { 
        c = cs.getConnection(); 
       } 
       SQLLogEntry entry = entries.remove(); 
       if (null != entry) { 
        try { 
         write(entry, c); //find usages 
        } 
        catch (SQLException ex) { 
         writeLogFile("Could not write entry to SQL", ex); 
        } 
       } 
      } 
      if (null != c) { 
       try { 
        c.commit(); 
       } 
       catch (SQLException ex) { 
        writeLogFile("Could commit to SQL", ex); 
        try { 
         c.rollback(); 
        } 
        catch (SQLException ex1) { 
        } 

        // log 
        final StringWriter err = new StringWriter();       
        ex.printStackTrace(new PrintWriter(err)); 
        EditorTransactionUtil.writeLogFile(err.toString());       
        // for user 
        final String msg = "Exception: " + EditorUtil.getErrorMessage(ex.getMessage());       
        try { 
         SwingUtilities.invokeAndWait(() -> { 
          JOptionPane.showMessageDialog(null, msg); 
         }); 
        } 
        catch (Throwable ex1) { 
        } 
       } 
       finally { 
        cs.returnConnection(c); 
       } 
       c = null; 
      } 

      synchronized(entries) { 
       try { 
        entries.wait(1000); 
       } 
       catch (InterruptedException ex) { 
        // This is a workaround to process this loop... 
       } 
      } 
     } 
     writeLogFile("SQLMsgLogger run loop stopping..."); 
    } 
+0

你试试catch块你的意思是?其中有很多...也可能是StackOverflow不是要求代码推荐/审查的最佳社区。 – n247s

+0

其他'entries'可能被重新分配/调用'entries.notify()'或类似的,同步的。我不知道'entries'是什么,但是应该使用一些并发能力的队列。整个同步块应该消失。 –

+0

这一个:'catch(InterruptedException ex){//这是一个解决方法来处理这个循环...}' – sixtytrees

回答

1

此代码的问题从这里开始。

If(running) return; 
running=true; 

这显然是试图确保只有一个线程执行。这是检查并发性的错误方法。当if检查结束时,第二步可能会启动,但分配尚未开始。你需要使用syncronizible接口。

至于配置的try catch块 - 正如Konrad指出的那样,如果没有Thread.interrupt()调用,它将不会执行。它可能是以前版本遗留的死代码。

相关问题