更新时间:2018年12月19日15时02分 来源:传智播客 浏览次数:
01 02 03 04 05 06 07 08 09 10 11 12 | public final class SessionFactoryImpl implements SessionFactoryImplementor{ private final transient CurrentSessionContext currentSessionContext; public SessionFactoryImpl( final MetadataImplementor metadata, SessionFactoryOptions options) { LOG.debug( "Building session factory" ); ...省略大量代码 currentSessionContext = buildCurrentSessionContext(); ...省略大量代码 } } |
1 2 3 | public ThreadLocalSessionContext(SessionFactoryImplementor factory) { super ( factory ); } |
1 2 3 4 5 6 7 8 | public abstract class AbstractCurrentSessionContext implements CurrentSessionContext { private final SessionFactoryImplementor factory; protected AbstractCurrentSessionContext(SessionFactoryImplementor factory) { this .factory = factory; } ..... } |
01 02 03 04 05 06 07 08 09 10 11 | public abstract class AbstractCurrentSessionContext implements CurrentSessionContext { private final SessionFactoryImplementor factory; protected AbstractCurrentSessionContext(SessionFactoryImplementor factory) { this .factory = factory; } public SessionFactoryImplementor factory() { return factory; } .... } |
01 02 03 04 05 06 07 08 09 10 11 | private static Session existingSession(SessionFactory factory) { final Map sessionMap = sessionMap(); if ( sessionMap == null ) { return null ; } return (Session) sessionMap.get( factory ); } protected static Map sessionMap() { return CONTEXT_TL.get(); } |
1 | private static final ThreadLocal<Map> CONTEXT_TL = new ThreadLocal<Map>(); |
什么是ThreadLocal
ThreadLocal是一个本地线程副本变量工具类。主要用于将私有线程和该线程存放的副本对象做一个映射,各个线程之间的变量互不干扰,在高并发场景下,可以实现无状态的调用,特别适用于各个线程依赖不通的变量值完成操作的场景。
1 2 3 4 5 6 7 8 | private static void doBind(org.hibernate.Session session, SessionFactory factory) { Map sessionMap = sessionMap(); if ( sessionMap == null ) { sessionMap = new HashMap(); CONTEXT_TL.set( sessionMap ); } sessionMap.put( factory, session ); } |