講解Hibernate ThreadLocal
Hibernate有很多值得學(xué)習(xí)的地方,這里我們主要介紹Hibernate ThreadLocal,包括介紹Hibernate官方開(kāi)發(fā)手冊(cè)標(biāo)準(zhǔn)示例等方面。
Hibernate ThreadLocal
它會(huì)為每個(gè)線程維護(hù)一個(gè)私有的變量空間。實(shí)際上, 其實(shí)現(xiàn)原理是在JVM 中維護(hù)一個(gè)Map,這個(gè)Map的key 就是當(dāng)前的線程對(duì)象,而value則是 線程通過(guò)Hibernate ThreadLocal.set方法保存的對(duì)象實(shí)例。當(dāng)線程調(diào)用Hibernate ThreadLocal.get方法時(shí), Hibernate ThreadLocal會(huì)根據(jù)當(dāng)前線程對(duì)象的引用,取出Map中對(duì)應(yīng)的對(duì)象返回。
這樣,Hibernate ThreadLocal通過(guò)以各個(gè)線程對(duì)象的引用作為區(qū)分,從而將不同線程的變量隔離開(kāi)來(lái)。
Hibernate官方開(kāi)發(fā)手冊(cè)標(biāo)準(zhǔn)示例:
- public class HibernateUtil {
- private static SessionFactory sessionFactory;
- static {
- try {
- // Create the SessionFactory sessionFactory = new Configuration().
configure().buildSessionFactory();- }
- catch (HibernateException ex) {
- throw new RuntimeException( "Configuration problem: " + ex.getMessage(), ex );
- }
- }
- public static final ThreadLocal session = new ThreadLocal();
- public static Session currentSession() throws HibernateException {
- Session s = (Session) session.get();
- // Open a new Session, if this Thread has none yet if (s == null) {
- s = sessionFactory.openSession();
- session.set(s);
- }
- return s;
- }
- public static void closeSession() throws HibernateException {
- Session s = (Session) session.get();
- session.set(null);
- if (s != null) s.close();
- }
- }
通過(guò)filter實(shí)現(xiàn)session的重用:
- public class PersistenceFilter implements Filter {
- protected static ThreadLocal hibernateHolder = new ThreadLocal();
- public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)- throws IOException,ServletException {
- hibernateHolder.set(getSession());
- try {
- ……
- chain.doFilter(request, response);
- ……
- }
- finally {
- Session sess = (Session)hibernateHolder.get();
- if (sess != null) { hibernateHolder.set(null);
- try { sess.close(); } catch (HibernateException ex) {
- throw new ServletException(ex);
- }
- }
- }
- }
- ……
- }
【編輯推薦】