Facilitate the management of hibernate sessions in threadlocal Mode

Source: Internet
Author: User

When we use hibernate to develop the DaO module, we have the most dealings with sessions, so how to reasonably manage sessions and avoid frequent session creation and destruction, it is very important to improve the system performance. We know that the session is created by sessionfactory, and the implementation of sessionfactory is thread-safe. multiple concurrent threads can simultaneously access one sessionfactory and obtain the session instance from it, is session thread-safe? Unfortunately, the answer is no. The session contains state information related to database operations. If multiple threads use a session instance for crud at the same time, data access may be disordered, can you imagine how a thread that cannot predict the execution sequence operates on one of your records?
Among the many management solutions of the session, we are going to know a solution named threadlocal.
As early as the launch of Java, the Java platform introduced a new support: Java. Lang. threadlocal, which provided us with a new choice when writing multi-threaded programs. What is threadlocal? In fact, threadlocal is not a local implementation version of a thread. It is not a thread, but a Thread Local
Variable (thread local variable ). It may be more appropriate to name it threadlocalvar. Threadlocal is a simple function. It provides a copy of the variable value for every thread that uses the variable. Each thread can change its own copy independently, it does not conflict with copies of other threads. From the thread perspective, it seems that every thread has a variable.
How does threadlocal maintain copies of variables for each thread? In fact, the implementation idea is very simple. There is a map in the threadlocal class, which is used to store copies of the variables of each thread. For example, the following example is implemented (for simplicity, the generic type of the set is not taken into account ):

Public class threadlocal {
Private map values = collections. synchronizedmap (New hashmap ());
Public object get (){
Thread currentthread = thread. currentthread ();
Object result = values. Get (currentthread );
If (result = NULL &&! Values. containskey (currentthread )){
Result = initialvalue ();
Values. Put (currentthread, result );
}
Return result;
}
Public void set (Object newvalue ){
Values. Put (thread. currentthread (), newvalue );
}
Public object initialvalue (){
Return NULL;
}
}
So how to use threadlocal to manage sessions? In the example in the hibernate official documentation manual, a good example is provided to maintain the session through threadlocal:

Public class hibernateutil {
Public static final sessionfactory;
Static {
Try {
Sessionfactory = new configuration (). Configure ()
. Buildsessionfactory ();
} Catch (throwable ex ){
Throw new exceptionininitializererror (Ex );
}
}
Public static final threadlocal <session> session =
New threadlocal <session> ();

Public static session currentsession () throws hibernateexception {
Session S = session. Get ();
If (S = NULL ){
S = sessionfactory. opensession ();
Session. set (s );
}
Return S;
}
Public static void closesession () throws hibernateexception {
Session S = session. Get ();
If (s! = NULL ){
S. Close ();
}
Session. Set (null );
}
}
With the help of the tool class above, we can achieve session sharing within the thread range, thus avoiding frequent thread creation and destruction of session instances. Of course, do not forget to close the session after use. I want to talk more about it here. Maybe most of the time our Dao won't involve multithreading. For example, we won't write the DaO code in the servlet, which is not a good design, I usually access Dao methods in service-layer code. However, I suggest using the above tool class to manage sessions. After all, we should not only consider what we do for ourselves today, but also what we do for ourselves tomorrow!

Source: http://blog.csdn.net/sole_ghost/article/details/1566599

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.