gpt4 book ai didi

java - 在 ThreadLocal 中包装 JDBC 连接单例

转载 作者:行者123 更新时间:2023-11-29 05:40:42 24 4
gpt4 key购买 nike

在阅读第一部分后,我正在开发使用普通 JDBC 的小型 CRUD 应用程序,以及基于 Connection 枚举的单例的 Java Concurrency in Practice我只是喜欢 ThreadLocal 编写线程安全代码的方法,我的问题是:

ThreadLocal 中包装全局 JDBC 连接时被认为是一种好的做法?

最佳答案

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

很大程度上取决于细节。如果有大量线程,那么每个线程都将打开自己的连接,这可能会让人望而却步。然后,当线程处于 hibernate 状态时,您将拥有停滞不前的连接。

最好使用可重入的连接池。然后您可以重用已经打开但当前未使用的连接,但将连接数限制为同时工作所需的最少连接数。 Apache's DBCP是一个很好的例子,并且经过深思熟虑。

引用他们的文档:

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.

关于java - 在 ThreadLocal 中包装 JDBC 连接单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17703263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com