[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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值