FastThreadLocal原理
生活随笔
收集整理的這篇文章主要介紹了
FastThreadLocal原理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、ThreadLocal的原理以及存在的問題
a.?每個線程內部維護了一個ThreadLocal.ThreadLocalMap類型的變量
b.?ThreadLocalMap 的 key 為 ThreadLocal,value為對應的變量
c.?對ThreadLocal進行get/set操作時,會先獲取當前Thread內部的ThreadLocal.ThreadLocalMap,然后以ThreadLocal為key,從這個Map中獲取對應的value
設計理念:
a.?ThreadLocal中的數據實際存放于Thread中,線程死亡時,這些數據會被自動釋放,減小了開銷
b.?一般來說,一個ThreadLocal對應的Thread數量遠多于一個Thread所對應的ThreadLocal數量,因此Thead內部維護的ThreadLocal.ThreadLocalMap的長度一般來說是較短的,尋址快速
?
1. ThreadLocal#get的問題
/*** Get the entry associated with key. This method* itself handles only the fast path: a direct hit of existing* key. It otherwise relays to getEntryAfterMiss. This is* designed to maximize performance for direct hits, in part* by making this method readily inlinable.** @param key the thread local object* @return the entry associated with key, or null if no such*/private Entry getEntry(ThreadLocal<?> key) {int i = key.threadLocalHashCode & (table.length - 1);//ThreadLocal的threadLocalHashCode是在定義ThreadLocal時產生的一個偽隨機數Entry e = table[i];if (e != null && e.get() == key)return e;elsereturn getEntryAfterMiss(key, i, e);}/*** 使用線性探測法處理未命中的情況* 在未命中的情況下,可能會退化到O(n)的時間復雜度*/private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {Entry[] tab = table;int len = tab.length;while (e != null) {ThreadLocal<?> k = e.get();if (k == key)return e;if (k == null)expungeStaleEntry(i);//由于ThreadLocalMap中的Entry擴展于WeakReference,設置為null,方便回收elsei = nextIndex(i, len);//查找ThreadLocalMap中的下一個元素,直到命中為止(線性探測法)e = tab[i];}return null;}?
?
?
二、FastThreadLocal
?FastThreadLocal的構造方法中,會為當前FastThreadLocal分配一個index,這個index是由一個全局唯一的static類型的AtomInteger產生的,可以保證每個FastThreadLocal的index都不同
?
參考:
ThreadLocal原理
總結
以上是生活随笔為你收集整理的FastThreadLocal原理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TransmittableThreadL
- 下一篇: TransmittableThreadL