finally 块是关闭数据库连接的正确位置吗?
我已经完成了一些教程。
他们说通过finally块关闭数据库连接。
但我心里有一个问题:
考虑一个场景,其中两个线程正在一个线程上主动读取 连接,一个线程完成他的工作并关闭 联系。那么另一个人会怎样呢?
第二个线程能够完成他的任务吗?
如果我的问题无效,请告诉我,并请告诉我最好的解决方案。
Possible Duplicate:
Is java.sql.Connection thread safe?
I have gone through some tutorials.
They said to close the database connection through finally block.
But I have a question on my mind:
Think about a scenario where two threads are actively reading on one
connection and one thread finishes his work and closes the
connection. So what happens to the other?
Is the second thread able to complete his task?
Please let me know if my question is not valid and please let me know the best solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,
finally
块是关闭Connection
和其他 JDBC 资源的正确方法。您应该避免在线程之间共享此类对象;虽然它们可能是线程安全的,但它们不适合以这种方式使用。一项 JDBC 规范 说:“实际上,我们期望大多数 JDBC 对象只能以单线程方式访问。”
如果您有多个线程使用同一数据库,请创建一个连接池,并允许每个线程独占访问
Connection
及其附属资源。Yes, a
finally
block is the correct way to close aConnection
and other JDBC resources.You should avoid sharing such objects between threads; while they are probably thread-safe, they are not intended to be used in this way. One JDBC specification says, "In practice we expect that most of the JDBC objects will only be accessed in a single threaded way."
If you have multiple threads using the same database, create a pool of connections, and allow each thread exclusive access to a
Connection
and its subsidiary resources.