简体   繁体   English

在ThreadLocal中包装JDBC连接单例

[英]Wrapping a JDBC Connection singleton in a ThreadLocal

I'm working on small CRUD application that use plain JDBC , with a Connection enum-based singleton, after reading the first part of Java Concurrency in Practice I just liked the ThreadLocal approach to write thread-safe code, my question is : 我正在研究使用普通JDBC小型CRUD应用程序,以及基于Connection枚举的单例,在阅读实践中Java Concurrency的第一部分之后,我只是喜欢使用ThreadLocal编写线程安全代码的方法,我的问题是:

When wrapping global JDBC connection in a ThreadLocal considered a good practice ? ThreadLocal包装全局JDBC连接被认为是一种好习惯吗?

When wrapping global JDBC connection in a ThreadLocal considered a good practice ? 在ThreadLocal中包装全局JDBC连接被认为是一种好习惯吗?

Depends a lot on the particulars. 取决于细节。 If there are a large number of threads then each one of them is going to open up their own connection which may be prohibitive. 如果存在大量线程,那么每个线程将打开它们自己的连接,这可能是禁止的。 Then you are going to have connections that stagnate as threads lie dormant. 然后,当线程处于休眠状态时,您将会断开连接。

It would be better to use a reentrant connection pool. 最好使用可重入的连接池。 Then you can reuse connections that are already open but not currently in use but limit the number of connections to the minimum you need to work concurrently. 然后,您可以重用已打开但当前未使用的连接,但将连接数限制为您需要同时工作的最小连接数。 Apache's DBCP is a good example and is well thought of. Apache的DBCP就是一个很好的例子,并且经过深思熟虑。

To quote from their docs: 引用他们的文档:

Creating a new connection for each user can be time consuming (often requiring multiple seconds of clock time), in order to perform a database transaction that might take milliseconds. 为每个用户创建新连接可能非常耗时(通常需要多秒的时钟时间),以便执行可能需要几毫秒的数据库事务。 Opening a connection per user can be unfeasible in a publicly-hosted Internet application where the number of simultaneous users can be very large. 在公共托管的Internet应用程序中,每个用户打开一个连接可能是不可行的,因为同时用户的数量可能非常大。 Accordingly, developers often wish to share a "pool" of open connections between all of the application's current users. 因此,开发人员通常希望在所有应用程序的当前用户之间共享打开连接的“池”。 The number of users actually performing a request at any given time is usually a very small percentage of the total number of active users, and during request processing is the only time that a database connection is required. 在任何给定时间实际执行请求的用户数通常占活动用户总数的很小百分比,并且在请求处理期间是唯一需要数据库连接的时间。

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

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