Hibernate uses ThreadLocal mode (thread local variable mode) to manage sessions

Source: Internet
Author: User

Hibernate uses ThreadLocal mode (thread local variable mode) to manage sessions
1. Understanding of managing sessions in ThreadLocal mode (thread local variable Mode)

(1) how to reasonably manage sessions during Hibernate development to avoid frequent creation and destruction of sessions is very important for improving system performance!

(2) 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 Session instances from it, however, it is a pity that the Session is not thread-safe.

(3) The Session contains state information related to database operations. If multiple threads simultaneously use one Session instance for CRUD (Database addition, deletion, modification, and query ), it is very likely that it will lead to confusion in data access. We simply cannot imagine the situations where the threads that you cannot predict the execution order operate on one of your records!

(4) among the many Session management solutions, we know that the ThreadLocal mode is a good solution in today's learning. I would like to share it with you!

(5) The first thing we need to understand is that 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 ). The ThreadLocal function is very simple. It provides a copy of the variable value for every thread that uses a 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.

(6) More specifically, ThreadLocal is not equivalent to the thread member variable. ThreadLocal provides the thread local variable. This local variable is different from the general member variable. When ThreadLocal variables are used by multiple threads, each thread can only get a copy of the variable. This is the description in Java API, but more accurately, it should be the internal Registry (Map But ThreadLocal is indeed a variable. this is the essence!

(7) Principle of ThreadLocal: there is a Map in the ThreadLocal class to store copies of the variables of each thread. For example, the following example is implemented:

public class ThreadLocal {private Map values = Collections.synchronizedMap(new HashMap());public Object get() {Thread curThread = Thread.currentThread();Object o = values.get(curThread);if (o == null && !values.containsKey(curThread)) {o = initialValue();values.put(curThread, o);}values.put(Thread.currentThread(), newValue);return o;}public Object initialValue() {return null;}}

 

Ii. Code display

(1) The code for managing sessions in ThreadLocal mode (thread local variable mode) is as follows:

 

Package com. lc. util; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. cfg. configuration;/*** the upgraded MySessionFactory Thread Local Mode * @ author xuliugen */public class HibernateUtil {private static SessionFactory sessionFactory = null; // use the local thread mode private static ThreadLocal
 
  
ThreadLocal = new ThreadLocal
  
   
();/** Default constructor */private HibernateUtil () {}/ ** static code block */static {sessionFactory = new Configuration (). configure (). buildSessionFactory ();}/** get the new session */public static Session openSession () {return sessionFactory. openSession ();}/** get the session associated with the thread */public static Session getCurrentSession () {Session session = threadLocal. get (); // determine whether to obtain if (session = null) {session = sessionFactory. openSession (); // put the session in threadLocal, which is equivalent to the session already bound to threadLocal by the thread. set (session) ;}return session ;}}
  
 

 

(2) The test code is as follows:

 

Package com. lc. view; import org. hibernate. session; import com. lc. util. hibernateUtil; public class TestHibernateUtil {public static void main (String [] args) {Session s1 = HibernateUtil. getCurrentSession (); Session s2 = HibernateUtil. getCurrentSession (); System. out. println (s1.hashCode () ++ s2.hashCode ();/** 1432950766 1432950766 * The result is that the two hashcodes are the same and prove to be thread-related */}}

 

 

 

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.