java - 跨线程共享一个 jdbc "Connection"

标签 java multithreading jdbc transactions

我有一个定期运行的主线程。它使用 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/

相关文章:

multithreading - 线程是否立即启动

java - 连接空闲后出现 SQLException

java - Tomcat 在哪里配置示例 webapp 的上下文路径?

java - 寻找 Dagger 辅助注入(inject)的示例

java - 如何将文件从SpringBoot项目资源内的子文件夹复制到资源内的另一个子文件夹

java - Telegram parse_mode Markdown 和 HTML JAVA

c - 如何向现有可变参数列表添加新参数?

c# - 多线程共享计数器和List集合变量

java - Hibernate只读实体表示通过删除数据库快照来节省内存

java - createDatabaseIfNotExist=true 在 maven 项目的 .properties 文件中不起作用