【java基础】ThreadLocal的实现原理
【一】:ThreadLocal对象的大体实现原理
===>当前线程对象有一个ThreadLocal.ThreadLocalMap属性。
===>声明的ThreadLocal对象最终存储在当前线程对象的属性ThreadLocalMap集合中。
===>ThreadLocalMap集合中的底层是一个Entry数组。每一个ThreadLocal对象经过属性nextHashCode属性计算出当前对象的hashCode决定存储位置。
===>Entry对象存储ThreadLocal对象和要与当前线程绑定的数据。
【二】:ThreadLocal在springAop的事务管理中的应用案例
===>spring的事务管理器类org.springframework.transaction.support.TransactionSynchronizationManager中就运用ThreadLocal对象绑定当前线程数据库事务信息。
===>org.springframework.core.NamedThreadLocal类
===>TransactionSynchronizationManager中绑定了当前线程的数据源,当前线程是否存在活动中的事务,当前线程在事务执行过程中的观察者事件,当前线程是否是只读事务,当前线程事务的名字,当前线程的事务隔离级别。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public abstract class TransactionSynchronizationManager { private static final Log logger = LogFactory.getLog(TransactionSynchronizationManager.class); private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal<Map<Object, Object>>("Transactional resources"); private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = new NamedThreadLocal<Set<TransactionSynchronization>>("Transaction synchronizations"); private static final ThreadLocal<String> currentTransactionName = new NamedThreadLocal<String>("Current transaction name"); private static final ThreadLocal<Boolean> currentTransactionReadOnly = new NamedThreadLocal<Boolean>("Current transaction read-only status"); private static final ThreadLocal<Integer> currentTransactionIsolationLevel = new NamedThreadLocal<Integer>("Current transaction isolation level"); private static final ThreadLocal<Boolean> actualTransactionActive = new NamedThreadLocal<Boolean>("Actual transaction active");
【三】:ThreadLocal在项目中的应用
===>ThreadLocalContext类的代码
===>ThreadLocalContext可以保存当前线程一些需要上下文存储数据。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class MyThreadContext { private Map<Object,Object> myData = new HashMap<Object,Object>(); public void put(Object key, Object message){ myData.put(key, message); } public Object get(Object key){ return myData.get(key); } public <T> T get(Object key,Class<T> clazz){ return (T) myData.get(key); } public static MyThreadContext getContext(){ return threadContext.get(); } public static void clearContext(){ threadContext.remove(); } private static ThreadLocal<ThreadContext> threadContext = new ThreadLocal<ThreadContext>() { protected ThreadContext initialValue() { return new ThreadContext(); } }; }
为什么ThreadLocalMap的静态内部类Entry要继承WeakReference<ThreadLocal<?>>?