简体   繁体   English

使用多个数据库连接会导致死锁

[英]Using multiple db connections causes deadlock

To resolve the issue mentioned here . 解决这里提到的问题。

We are creating and using 2 same JDBC Singleton Connections(Regular, Proxy). 我们正在创建并使用2个相同的JDBC单例连接(常规,代理)。

  • But by doing so we are facing deadlock when we try to use both connections consecutively on same table for doing multiple inserts and updates. 但是这样做时,当我们尝试在同一表上连续使用两个连接进行多次插入和更新时,我们将面临死锁。
  • When this happens, I cannot run any queries from the DB tool (Aqua Data Studio) as well. 发生这种情况时,我也无法从数据库工具(Aqua Data Studio)运行任何查询。
  • My assumption is that it waits indefinitely for other connection to release lock. 我的假设是,它无限期地等待其他连接释放锁。

Note: We are not dealing with multi-threading here. 注意:这里我们不处理多线程。

Issue: 问题:

//  Auto Commit false
// Singelton
Connection connection = getConnection();  //same        

// Auto Commit true
// // Singelton
Connection proxyConnection= getConnection();  //same

PreparedStatement ps = null;

try{
   connection.setAutoCommit(false);

   //Step 1
   String sql = getQuery(); 
   ps = proxyConnection.prepareStatement(sql); 
   ps.executeUpdate();        
   .
   .
   //Step 2
   // if I don't execute this step everything works fine.  
   sql = getTransctionQuery();              
   ps = connection.prepareStatement(sql); 
   ps.executeUpdate();   

   .
   .
   //Step 3
   sql = getQuery(); 
   ps = proxyConnection.prepareStatement(sql);  
   ps.executeUpdate();  // this line never completes (if Step 2 runs)

}catch(){
   connection.rollback(); //Doesn’t rollback step 1 and understandably step 2.
}
finally{
   connection.close();  //cleanup code
   proxyConnection.close();
}

Question: 题:

  • How to resolve this issue? 如何解决这个问题?
  • How to make sure different connections, though they are creating using same class loader, won't lock database/table. 尽管要确保使用相同的类加载器创建不同的连接,但如何确保它们不会锁定数据库/表。

Thanks 谢谢

I'm no expert here but I used to have problems with Oracle DB when running a query and then forgetting to commit (or cancel). 我不是专家,但是在运行查询然后忘记提交(或取消)时,我曾经在Oracle DB上遇到问题。 So I think that the fact that you didn't commit after step 2 locks the database for the next access. 因此,我认为您没有在步骤2之后提交的事实将锁定数据库以进行下一次访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM