1、ThreadlLocal
简介:ThreadLocal提供线程的局部变量,每个线程都可以通过get()和set()对局部变量进行操作而不会对其他线程的局部变量产生影响,实现了线程之间的数据隔离。e.g. 数据库的连接池管理。
-
原理:
- 每个Thread维护着一个ThreadLocalMap的引用
- ThreadLocalMap是ThreadLocal的内部类,用Entry来进行存储
- 调用ThreadLocal的set()方法时,实际上就是往ThreadLocalMap设置值,key是ThreadLocal对象,值是传递进来的对象
- 调用ThreadLocal的get()方法时,实际上就是往ThreadLocalMap获取值,key是ThreadLocal对象
- ThreadLocal本身并不存储值,它只是作为一个key来让线程从ThreadLocalMap获取value。
public void set(T value) { // 得到当前线程对象 Thread t = Thread.currentThread(); // 这里获取ThreadLocalMap ThreadLocalMap map = getMap(t); // 如果map存在,则将当前线程对象t作为key,要存储的对象作为value存到map里面去 if (map != null) map.set(this, value); else createMap(t, value); } static class ThreadLocalMap { /** * The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object). Note that null keys (i.e. entry.get() * == null) mean that the key is no longer referenced, so the * entry can be expunged from table. Such entries are referred to * as "stale entries" in the code that follows. */ static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } } //....很长 } void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; } ThreadLocal.ThreadLocalMap threadLocals = null
不足:无法完成父子线程之间的数据传递。
2、InheritableThreadLocal
简介:ThreadLocal的升级版,jdk原生,实现了父子线程之间的数据传递。
-
原理:重新开辟一块空间(InheritableThreadLocal)用于存储父子线程共用的数据隔离空间。重写了ThreadLocal的三个方法,当创建新线程的时候,将父线程的ThreadLocal值拷贝到子线程。
/** * 该函数在父线程创建子线程,向子线程复制InheritableThreadLocal变量时使用 */ protected T childValue(T parentValue) { return parentValue; } /** * 由于重写了getMap,操作InheritableThreadLocal时, * 将只影响Thread类中的inheritableThreadLocals变量, * 与threadLocals变量不再有关系 */ ThreadLocalMap getMap(Thread t) { return t.inheritableThreadLocals; } /** * 类似于getMap,操作InheritableThreadLocal时, * 将只影响Thread类中的inheritableThreadLocals变量, * 与threadLocals变量不再有关系 */ void createMap(Thread t, T firstValue) { t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue); } public class Thread implements Runnable { ......(其他源码) /* * 当前线程的ThreadLocalMap,主要存储该线程自身的ThreadLocal */ ThreadLocal.ThreadLocalMap threadLocals = null; /* * InheritableThreadLocal,自父线程集成而来的ThreadLocalMap, * 主要用于父子线程间ThreadLocal变量的传递 * 本文主要讨论的就是这个ThreadLocalMap */ ThreadLocal.ThreadLocalMap inheritableThreadLocals = null; ......(其他源码) } /** * 初始化一个线程. * 此函数有两处调用, * 1、上面的 init(),不传AccessControlContext,inheritThreadLocals=true * 2、传递AccessControlContext,inheritThreadLocals=false */ private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) { ......(其他代码) if (inheritThreadLocals && parent.inheritableThreadLocals != null) this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals); ......(其他代码) }
不足:无法完成线程池间的数据传递。
3、Transmittable-Thread-Local
InheritableThreadLocal value 串位问题的根本原因在于它依赖 Thread 类本身的机制传递 value, 而 Thread 类由于其于线程池内 “复用存在” 的形式而导致 InheritableThreadLocal 的机制失效; 所以针对 InheritableThreadLocal 的改进, 突破点就在于如何摆脱对 Thread 类的依赖。
简介:阿里开源组件,继承自InheritableThreadLocal,实现了父子线程在线程池中的数据传递。
-
原理:在提交任务给线程池时,将ThreadLocal数据一起提交,相当于重新set一次ThreadLocal,「把任务提交给线程池时的ThreadLocal值传递到 任务执行时」。
-
与InheritableThreadLocal类似,单独搞了一块空间,维护一个全局的静态变量holder,存储所有TransmittableThreadLocal实例
static ThreadLocal<Map<TransmittableThreadLocal<?>, ?>> holder = new ThreadLocal<Map<TransmittableThreadLocal<?>, ?>>() { @Override protected Map<TransmittableThreadLocal<?>, ?> initialValue() { return new WeakHashMap<TransmittableThreadLocal<?>, Object>(); } };
-
提供一个 copy() 方法实时复制所有 TransmittableThreadLocal 实例及其在当前线程的 value
static Map<TransmittableThreadLocal<?>, Object> copy() { Map<TransmittableThreadLocal<?>, Object> copy = new HashMap<TransmittableThreadLocal<?>, Object>(); for (TransmittableThreadLocal<?> threadLocal : holder.get().keySet()) { copy.put(threadLocal, threadLocal.copyValue()); } return copy; }
-
封装了原始的 Runnable 和 Callable,将当前线程下所有的 TransmittableThreadLocal 实例及其对应的 value, 放到了一个 AtomicReference 包装的 map 之中, 这样就完成了由父线程向 Runnable的value 传递
private TtlRunnable(Runnable runnable, boolean releaseTtlValueReferenceAfterRun) { this.copiedRef = new AtomicReference<Map<TransmittableThreadLocal<?>, Object>>(TransmittableThreadLocal.copy()); this.runnable = runnable; this.releaseTtlValueReferenceAfterRun = releaseTtlValueReferenceAfterRun; }
-
关键的 run() 方法的处理
public void run() { Map<TransmittableThreadLocal<?>, Object> copied = copiedRef.get(); // 非核心逻辑已省略 ...... Map<TransmittableThreadLocal<?>, Object> backup = TransmittableThreadLocal.backupAndSetToCopied(copied); try { runnable.run(); } finally { TransmittableThreadLocal.restoreBackup(backup); } }
-
不足:对hystrix修饰的线程池无效,因为hytrix做了线程隔离。
参考资料:
- https://github.com/alibaba/transmittable-thread-local
- https://fredal.xin/async-threadlocal-in-all-link-tracking
- https://cloud.tencent.com/developer/article/1162226*
- http://cxytiandi.com/blog/detail/18782
- https://juejin.im/post/5ac2eb52518825555e5e06ee
- https://zshell.cc/2018/08/03/jdk--ThreadLocal%E7%9B%B8%E5%85%B3%E7%9F%A5%E8%AF%86%E5%85%A8%E6%A2%B3%E7%90%86/