多个线程同时使用相同的JDBC连接 [英] Concurrent use of same JDBC connection by multiple threads

查看:587
本文介绍了多个线程同时使用相同的JDBC连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力更好地理解如果多个线程同时使用相同的JDBC连接尝试执行不同的sql查询会发生什么。

I'm trying to better understand what will happen if multiple threads try to execute different sql queries, using the same JDBC connection, concurrently.


  • 结果是否在功能上正确?

  • Will the outcome be functionally correct?

性能影响是什么?

线程 A 是否必须等待线程 B 要完全完成查询吗?

Will thread A have to wait for thread B to be completely done with its query?

或者线程 A 能够在线程之后立即发送查询B 已经发送了它的查询,之后数据库将同时执行两个查询?

Or will thread A be able to send its query immediately after thread B has sent its query, after which the database will execute both queries in parallel?

我看到Apache DBCP使用同步协议来确保从池中删除的连接从池中删除,并且在它们关闭之前不可用。这似乎比它需要的更不方便。我正在考虑构建自己的池,只需创建一个静态的打开连接列表,并以循环方式分发它们。我不介意偶尔的性能下降,并且每次使用后不必关闭连接的便利性似乎非常吸引人。这样做有什么缺点吗?

I see that the Apache DBCP uses synchronization protocols to ensure that connections obtained from the pool are removed from the pool, and made unavailable, until they are closed. This seems more inconvenient than it needs to be. I'm thinking of building my own "pool" simply be creating a static list of open connections, and distributing them in a round-robin manner. I don't mind the occasional performance degradation, and the convenience of not having to close the connection after every use seems very appealing. Is there any downside to me doing this?

推荐答案

由于JDBC规范不能保证并发执行,这个问题可以解决只能通过测试你感兴趣的驱动程序或阅读它们的源代码来解答。

Since the JDBC spec doesn't give guarantees of concurrent execution, this question can only be answered by testing the drivers you're interested in, or reading their source code.

对于MySQL Connector / J,所有方法都是执行语句使用 synchronized 块锁定连接。也就是说,如果一个线程正在运行查询,则使用该连接的其他线程将被阻塞,直到完成。

In the case of MySQL Connector/J, all methods to execute statements lock the connection with a synchronized block. That is, if one thread is running a query, other threads using the connection will be blocked until it finishes.

这篇关于多个线程同时使用相同的JDBC连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆