gpt4 book ai didi

java - 方法中的 `try catch//this is a workaround`。应该如何重写呢?

转载 作者:行者123 更新时间:2023-12-01 09:36:03 28 4
gpt4 key购买 nike

项目源代码有一个用于 SQL 处理的 Java 方法。该方法确实有效,但它使用了一个有问题的解决方法:在方法的最后部分使用 try-catch block 来正常执行。正确的实现方法是什么?

    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...");
}

最佳答案

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

If(running) return;
running=true;

这显然是为了确保只有一个线程执行。这是检查并发性的错误方法。当 if 检查结束时,第二步可能会立即开始,但分配尚未开始。您需要使用可同步的接口(interface)。

至于已释放的 try catch block - 正如 Konrad 指出的那样,如果没有 Thread.interrupt() 调用,它不会被执行。它可能是以前版本留下的死代码。

关于java - 方法中的 `try catch//this is a workaround`。应该如何重写呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38918572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com