Facilitate Session management in ThreadLocal Mode

Source: Internet
Author: User
When we use Hibernate to develop the DAO module, we have the most dealings with sessions. Management To avoid frequent creation and destruction of sessions, it is very important to improve the system performance. In the past, the code was automatically completed through the eclipse plug-in. Of course Effect It is good, but it is always uncomfortable (not reading the lengthy code), so now I plan to implement the Session management code by myself.

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, a new support was introduced in the Java platform: Java . Lang. ThreadLocal provides us with a new option 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 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.

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 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 will not involve multithreading. For example, we will not write the DAO code in the Servlet, which is not good. Design , I usually access the DAO method in the 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!

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.