Vij*_*van 12 java multithreading transactions jdbc
我有一个定期运行的主线程.它使用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}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12606 次 |
| 最近记录: |