Use ThreadLocal to maintain Connection and localconnection

Source: Internet
Author: User

Use ThreadLocal to maintain Connection and localconnection

In previous projects, I have also used the transaction mechanism. In summary, there are three types of transactions (in essence, they are all the same, but their forms are different ):

First: directly write data in the database in the Stored Procedure (this is the simplest, which is not described here. The problem is that the Code cannot be reused at all, where you need to write SQL statements separately)

The second type: design with the idea of layering and encapsulate the method in layer D (this is similar to the problem of Directly Writing in the database, which is the same as the above-the reuse problem ).

Third: Write fine-grained operation methods on layer D, and start transaction assembly on the layer or other layers. This method often involves the Connection transfer problem, of course, in my original blog, I wrote it in static variables and used it directly at Layer D. Of course, thread security is not considered in this case. It is also very troublesome to transfer data.

We use ThreadLocal to maintain the Connection to avoid this situation.

ThreadLocal is easy to understand and take for granted as a "local thread ". In fact, ThreadLocal is not a Thread, but a local variable of the Thread. It may be easier to understand to name it ThreadLocalVariable.

This class provides thread-local variables. These variables are different from their common counterparts, becauseGetOrSetEach thread has its own local variable, which is independent of the initialization copy of the variable.

ThreadLocalInstances are usually private static fields in the class. They want to associate the state with a thread (for example, user ID or transaction ID), that is, they can share the resource in the same thread.

Use ThreadLocal to maintain Connection instances

Package com. hanyi. drp. util; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; /*** use ThreadLocal to maintain Connection * @ author hanyi **/public class ConnectionManage {// used to save connectionprivate static ThreadLocal <Connection> connectionHolder = new ThreadLocal <Connection> (); /*** Get Connection ** @ return */public static Connection Get Connection () {Connection conn = connectionHolder. get (); if (conn = null) {try {JdbcConfig jdbcConfig = XmlConfigReader. getInstance (). getJdbcConfig (); Class. forName (jdbcConfig. getDriverName (); conn = DriverManager. getConnection (jdbcConfig. getUrl (), jdbcConfig. getUserName (), jdbcConfig. getPassword ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} connectionHolder. set (conn) ;}return conn ;}// close the public static void closeConnection () {Connection conn = connectionHolder. get (); if (conn! = Null) {try {conn. close (); // clear ConnectionconnectionHolder from ThreadLocal. remove ();} catch (SQLException e) {e. printStackTrace () ;}}// close Statement (the object used to execute a static SQL Statement and return the result it generates .) Public static void close (Statement pstmt) {if (pstmt! = Null) {try {pstmt. close ();} catch (SQLException e) {e. printStackTrace () ;}}// close the result set public static void close (ResultSet rs) {if (rs! = Null) {try {rs. close ();} catch (SQLException e) {e. printStackTrace () ;}}// enable the public static void beginTransaction (Connection conn) {try {if (conn! = Null) {if (conn. getAutoCommit () {conn. setAutoCommit (false); // manually submit }}} catch (SQLException e) {}} // submit the transaction public static void commitTransaction (Connection conn) {try {if (conn! = Null) {if (! Conn. getAutoCommit () {conn. commit () ;}} catch (SQLException e) {}} // rollback transaction public static void rollbackTransaction (Connection conn) {try {if (conn! = Null) {if (! Conn. getAutoCommit () {conn. rollback () ;}} catch (SQLException e ){}}}

This operation completely solves the problem: 1. the fine-grained code is completely reused. 2. Ensures thread security. 3. Avoid passing parameters.




Private static String ThreadLocal <Connection> t1 = new ThreadLocal <Connectio

You can think of ThreadLocal as a local variable of a thread.
This statement declares a ThreadLocal variable t1. t1 can save the Connection type object for every thread that references this class. When multiple threads use this class, each thread can save its own Connection object in t1, and the Connection object in each thread will not be confused, when each thread needs to use its own Connection, it only needs to call t1.Get (), and the returned Connection must be the one saved by the current thread.
All in all, ThreadLocal is the local variable of the thread, and it is also generic. The type in <> is the type of the local variable. Use the Set method to Set the value of a local variable, and use the Get method to obtain the value of a local variable.

ThreadLocal

ThreadLocal refers to the current thread range, and the maintenance object is visible;
Using ThreadLocal to measure website traffic is certainly not acceptable. Each user accessing the server is a separate thread;
This class can be viewed as a container, just like domain objects such as the page domain and session domain. Now I can explain to you that the ThreadLocal object can be used to help control JDBC operations, ensure that multiple DAO accesses are operated in the same Connection object. That is to say, if multiple DAO (Service) needs to be operated in the same thing, the Connection object for the first operation can be saved in ThreadLocal, the same Connection is obtained from any DAO or Service;

Hope to help you

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.