1嘉抓、ThreadlLocal
簡介:ThreadLocal提供線程的局部變量填抬,每個線程都可以通過get()和set()對局部變量進行操作而不會對其他線程的局部變量產生影響佛玄,實現(xiàn)了線程之間的數(shù)據(jù)隔離婚夫。e.g. 數(shù)據(jù)庫的連接池管理新翎。
-
原理:
- 每個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
不足:無法完成父子線程之間的數(shù)據(jù)傳遞捧弃。
2赠叼、InheritableThreadLocal
簡介:ThreadLocal的升級版,jdk原生违霞,實現(xiàn)了父子線程之間的數(shù)據(jù)傳遞嘴办。
-
原理:重新開辟一塊空間(InheritableThreadLocal)用于存儲父子線程共用的數(shù)據(jù)隔離空間。重寫了ThreadLocal的三個方法买鸽,當創(chuàng)建新線程的時候涧郊,將父線程的ThreadLocal值拷貝到子線程。
/** * 該函數(shù)在父線程創(chuàng)建子線程眼五,向子線程復制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; ......(其他源碼) } /** * 初始化一個線程. * 此函數(shù)有兩處調用逗物, * 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); ......(其他代碼) }
不足:無法完成線程池間的數(shù)據(jù)傳遞失暴。
3、Transmittable-Thread-Local
InheritableThreadLocal value 串位問題的根本原因在于它依賴 Thread 類本身的機制傳遞 value, 而 Thread 類由于其于線程池內 “復用存在” 的形式而導致 InheritableThreadLocal 的機制失效; 所以針對 InheritableThreadLocal 的改進, 突破點就在于如何擺脫對 Thread 類的依賴微饥。
簡介:阿里開源組件逗扒,繼承自InheritableThreadLocal,實現(xiàn)了父子線程在線程池中的數(shù)據(jù)傳遞欠橘。
-
原理:在提交任務給線程池時矩肩,將ThreadLocal數(shù)據(jù)一起提交,相當于重新set一次ThreadLocal肃续,「把任務提交給線程池時的ThreadLocal值傳遞到 任務執(zhí)行時」黍檩。
-
與InheritableThreadLocal類似叉袍,單獨搞了一塊空間,維護一個全局的靜態(tài)變量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/