[Design Pattern] Thread Local Session Pattern

 

The Thread Local Session pattern makes use of the java.lang.ThreadLocal class to create a Session that is accessible from a single application thread. This is particularly convenient in multithreaded applications, such as web applications. The core of the pattern is defined in one class, shown in listing 8.9.
 
Listing 8.9 Thread Local Session provider:
package com.manning.hq.ch08;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ServiceLocator {
    private static final ThreadLocal t = new ThreadLocal();
    private static SessionFactory factory;
    static {
        try {
            factory = new Configuration().configure().buildSessionFactory();
        } catch ( HibernateException e ) {
            e.printStackTrace();
        }
    }
    public static Session getSession() throws HibernateException {
        Session s = ( Session ) t.get();
        if ( s == null ) {
            s = factory.openSession();
            t.set( s );
        }
        return s;
    }
    public void closeSession() {
        Session s = ( Session ) t.get();
        if ( s != null ) {
            try {
                s.close();
            } catch ( HibernateException e ) {
                e.printStackTrace();
            }
        }
        t.set( null );
    }
}
 
 
If there is any magic to the ServiceLocator class, it’s in how the ThreadLocal class behaves. By storing the initialized Session instance in the ThreadLocal variable, you are ensured that only one Session is created per request thread. When the Session is retrieved the first time, a new Session is opened by the SessionFactory and set in the ThreadLocal instance. Subsequent calls to getSession() return the same Session instance as long as the Session hasn’t been closed with a call to closeSession() .
Why is this valuable? DAOs frequently need to access the same Session object over multiple method calls, and the Thread Local Session pattern guarantees that behavior. Reusing the same Session during the life of an application thread also provides better performance compared with needlessly creating multiple Session s.
这个类叫做“SessionLocator”也许更好一些,因为它和Service Locator pattern中的那个ServiceLocator不是一个概念,实现也不一样,寡人原来还有点搞混呢。 >_<!!
简而言之:
这个类是用来把Session对象绑定到一个线程中,避免创建不必要的Session对象(通过使用java.lang.ThreadLocal类来实现);
Service Locator pattern中的那个ServiceLocator用来减少JNDI的查询次数(通过缓存[Cache]被请求过的对象来实现 )。
其实目的是一样的,都是减少不必要的开销,提高程序运行效率。
FROM:
Hibernate Quickly, Manning
by
Patrick Peak
Nick Heudecker

你可能感兴趣的:([Design Pattern] Thread Local Session Pattern)