我有一个定期运行的主线程。它使用 setAutoCommit(false) 打开一个连接,并作为引用传递给几个子线程以执行各种数据库读/写操作。在子线程中执行相当多的操作。在所有子线程完成他们的数据库操作后,主线程使用打开的连接提交事务。请注意,我在 ExecutorService 中运行线程。我的问题是,跨线程共享连接是否可取?如果"is",看看下面的代码是否正确地实现了它。如果“否”,在多线程场景中执行事务的其他方式是什么?欢迎评论/建议/新想法。伪代码...
Connection con = getPrimaryDatabaseConnection();
// let me decide whether to commit or rollback
con.setAutoCommit(false);
ExecutorService executorService = getExecutor();
// connection is sent as param to the class constructor/set-method
// the jobs uses the provided connection to do the db operation
Callable jobs[] = getJobs(con);
List futures = new ArrayList();
// note: generics are not mentioned just to keep this simple
for(Callable job:jobs) {
futures.add(executorService.submit(job));
}
executorService.shutdown();
// wait till the jobs complete
while (!executorService.isTerminated()) {
;
}
List result = ...;
for (Future future : futures) {
try {
results.add(future.get());
} catch (InterruptedException e) {
try {
// a jobs has failed, we will rollback the transaction and throw exception
connection.rollback();
result = null;
throw SomeException();
} catch(Exception e) {
// exception
} finally {
try {
connection.close();
} catch(Exception e) {//nothing to do}
}
}
}
// all the jobs completed successfully!
try {
// some other checks
connection.commit();
return results;
} finally {
try {
connection.close();
} catch(Exception e){//nothing to do}
}
最佳答案
我不建议您在线程之间共享连接,因为连接操作非常缓慢并且您的应用程序的整体性能可能会受到损害。
我宁愿建议你使用 Apache Connections Pool并为每个线程提供单独的连接。
关于java - 跨线程共享一个 jdbc "Connection",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897092/