简体   繁体   中英

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 :

When wrapping global JDBC connection in a ThreadLocal considered a good practice ?

When wrapping global JDBC connection in a ThreadLocal considered a good practice ?

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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