跨线程共享jdbc"连接"

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)

mik*_*ike 1

您可以创建一个代理类来保存 JDBC 连接并提供对其的同步访问。线程永远不应该直接访问连接。

根据您提供的用途和操作,您可以使用synchronized方法,或者如果需要锁定代理直到他离开某个状态,则锁定对象。


对于那些不熟悉代理设计模式的人。这里是维基文章。基本思想是代理实例隐藏另一个对象,但提供相同的功能。