我有一个定期运行的主线程。它使用 setAutoCommit(false) 打开一个连接,并作为引用传递给少数子线程以执行各种数据库读/写操作。在子线程中执行了相当数量的操作。在所有子线程完成它们的数据库操作后,主线程使用打开的连接提交事务。请注意,我在 ExecutorService 中运行线程。我的问题,是否建议跨线程共享连接?如果“是”,请查看以下代码是否正确实现它。如果“否”,在多线程场景中执行事务的其他方法是什么?欢迎评论/建议/新想法。伪代码...
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}
}