ThreadLocal類並不是用來解決多線程環境下的共享變量問題,而是用來提供線程局部變量。這些變量與普通的變量不同,因爲每個訪問一個變量的線程(通過其get或set方法)都有自己的、獨立初始化的變量副本。ThreadLocal實例通常是類中的私有靜態字段,希望將狀態與線程關聯(例如,用戶ID或事務ID)。每個線程都保持對線程本地變量的副本的隱式引用,只要線程是活的並且ThreadLocal實例是可訪問的;在線程離開之後,線程本地實例的所有副本都受到垃圾回收(除非存在對這些副本的其他引用)。
實現原理
ThreadLocal實現方式就是ThreadLocal類內部有一個線程安全的ThreadLocalMap,然後用ThreadLocal本身作爲Map的key,實例對象作爲Map的value,這樣就能達到各個線程的值隔離的效果。
ThreadLocalMap
ThreadLocalMap是用來存儲與線程關聯的value的哈希表,它具有HashMap的部分特性,比如容量、擴容、刪除等,它內部通過Entry類來存儲key和value。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** 與此ThreadLocal關聯的值. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
Entry繼承自WeakReference,可以知道,ThreadLocalMap是使用ThreadLocal的弱引用作爲Key的。如果一個ThreadLocal沒有外部關聯的強引用,那麼在虛擬機進行垃圾回收時,這個ThreadLocal會被回收,這樣,ThreadLocalMap中就會出現key爲null的Entry,這些key對應的value也就再無妨訪問,但是value卻存在一條從Current Thread過來的強引用鏈。因此只有當Current Thread銷燬時,value才能得到釋放。
ThreadLocalMap採用線性探查的方式來處理哈希衝突,所以會有一個while循環去查找對應的key,在查找過程中,若發現key爲null,即通過弱引用的key被回收,會調用expungeStaleEntry(int)方法,若key爲null,則該方法會清理與key對應的value以及Entry。
類名
public class ThreadLocal<T>
變量
/**
* ThreadLocals依賴於附加到每個線程哈希映射(thread.ThreadLocals和inheritablethrreadlocals)。
* ThreadLocal對象充當鍵,通過threadLocalHashCode進行搜索。
* 這是一個自定義散列代碼(僅在ThreadLocalMaps中有用),
* 它消除了在相同線程使用連續構造的threadlocal的常見情況下的衝突,
* 同時在不太常見的情況下保持良好的性能。
*/
private final int threadLocalHashCode = nextHashCode();
/**
* 下一個hash code。原子操作更新。從零開始.
*/
private static AtomicInteger nextHashCode =
new AtomicInteger();
/**
* 連續生成的散列碼之間的增量
*/
private static final int HASH_INCREMENT = 0x61c88647;
set(T value)
public void set(T value) {
//返回當前正在執行的線程對象的引用
Thread t = Thread.currentThread();
//獲取線程對應的ThreadLocalMap對象
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
當map爲null時,調用createMap創建一個map。
createMap(Thread t, T firstValue)
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
可以看出createMap是初始化當前線程的threadLocals變量。所以並不是ThreadLocal中存儲線程,而是線程中存儲ThreadLocal。
get()
public T get() {
//返回當前正在執行的線程對象的引用
Thread t = Thread.currentThread();
//獲取線程對應的ThreadLocalMap對象
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
簡單應用
很多時候我們會用SimpleDateFormat來格式化時間,而SimpleDateFormat其實是線程不安全的,我們可以用ThreadLocal封裝一個時間工具類。
public class DateUtil {
private static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>();
public static Date getNow() {
return Calendar.getInstance().getTime();
}
public static Date parse(String date, String pattern){
SimpleDateFormat simpleDateFormat = threadLocal.get();
if (simpleDateFormat == null){
simpleDateFormat = new SimpleDateFormat(pattern);
threadLocal.set(simpleDateFormat);
}
try {
return simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String format(Date date, String pattern){
SimpleDateFormat simpleDateFormat = threadLocal.get();
if (simpleDateFormat == null) {
simpleDateFormat = new SimpleDateFormat(pattern);
threadLocal.set(simpleDateFormat);
}
return simpleDateFormat.format(date);
}
}
源碼(1.8)
public class ThreadLocal<T> {
/**
* ThreadLocals依賴於附加到每個線程哈希映射(thread.ThreadLocals和inheritablethrreadlocals)。
* ThreadLocal對象充當鍵,通過threadLocalHashCode進行搜索。
* 這是一個自定義散列代碼(僅在ThreadLocalMaps中有用),
* 它消除了在相同線程使用連續構造的threadlocal的常見情況下的衝突,
* 同時在不太常見的情況下保持良好的性能。
*/
private final int threadLocalHashCode = nextHashCode();
/**
* 下一個hash code。原子操作更新。從零開始.
*/
private static AtomicInteger nextHashCode =
new AtomicInteger();
/**
* 連續生成的散列碼之間的增量
*/
private static final int HASH_INCREMENT = 0x61c88647;
/**
* 返回下一個hash值
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
/**
* 返回此線程局部變量的當前線程“初始值”。
*
* 此實現只返回null;如果希望線程局部變量具有null以外的值,
* 則必須進行子類化,並重寫此方法。通常,將使用匿名內部類
*/
protected T initialValue() {
return null;
}
/**
* 創建線程局部變量。變量的初始值是通過調用Supplier上的get方法來確定的。
* @param supplier 用於確定初始值的供應商
*/
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
return new SuppliedThreadLocal<>(supplier);
}
public ThreadLocal() {
}
/**
*返回此線程局部變量的當前線程副本中的值。
*如果變量沒有當前線程的值,則首先將其初始化爲調用initialValue方法返回的值
*/
public T get() {
//返回當前正在執行的線程對象的引用
Thread t = Thread.currentThread();
//獲取線程對應的ThreadLocalMap對象
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
/**
* 用於建立初始值的set()的變量
*/
private T setInitialValue() {
T value = initialValue();
//返回當前正在執行的線程對象的引用
Thread t = Thread.currentThread();
//獲取線程對應的ThreadLocalMap對象
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
/**
* 將此線程局部變量的當前線程副本設置爲指定值。
* 大多數子類無需重寫此方法,
* 只需依賴initialValue方法來設置線程局部變量的值。
*
* @param value 要存儲在此線程本地副本中的值
*/
public void set(T value) {
//返回當前正在執行的線程對象的引用
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
//獲取線程對應的ThreadLocalMap對象
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
/**
* 刪除此線程局部變量的當前線程值
*/
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
/**
* 獲取與ThreadLocal關聯的映射。在InheritableThreadLocal中重寫。
* @param t 當前線程
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* 創建與ThreadLocal關聯的映射。在InheritableThreadLocal中重寫
* @param t 當前線程
* @param firstValue 映射的初始項的值
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
/**
* 創建繼承的線程局部變量映射的工廠方法。設計爲僅從線程構造函數調用。
* @param parentMap 與父線程關聯的映射
* @return 包含父級可繼承綁定的映射
*/
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
return new ThreadLocalMap(parentMap);
}
/**
* childValue方法在子類InheritableThreadLocal中定義,
* 但在這裏是內部定義的,目的是提供CreateInheritabledMap工廠方法,
* 而無需在InheritableThreadLocal中對map類進行子類劃分。
*/
T childValue(T parentValue) {
throw new UnsupportedOperationException();
}
/**
* 從指定的Supplier獲取初始值的ThreadLocal的擴展。
*/
static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
private final Supplier<? extends T> supplier;
SuppliedThreadLocal(Supplier<? extends T> supplier) {
this.supplier = Objects.requireNonNull(supplier);
}
@Override
protected T initialValue() {
return supplier.get();
}
}
/**
*ThreadLocalMap是一個定製的散列映射,僅適用於維護線程本地值。
*在ThreadLocal類之外不作任何操作。該類是包私有的,允許在類線程中聲明字段。
*爲了幫助處理非常大且使用壽命長的用法,哈希表條目使用WeakReferences作爲鍵。
*但是,由於不使用引用隊列,因此只有當表開始耗盡空間時,才保證刪除過時的條目
*/
static class ThreadLocalMap {
/**
*此哈希映射中的條目使用其主ref字段作爲鍵(始終是ThreadLocal對象)
* 擴展WeakReference。請注意,
*空鍵(即entry.get()==null)意味着不再引用該鍵,
*因此可以從表中刪除該項。這些條目在下面的代碼中稱爲“過時條目”。
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** 與此ThreadLocal關聯的值。 */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* 初始容量必須是2的冪次方。
*/
private static final int INITIAL_CAPACITY = 16;
/**
* 根據需要調整大小。表的長度必須是2的冪次方。
*/
private Entry[] table;
/**
* table的大小
*/
private int size = 0;
/**
* 下一個要調整大小的大小值。
*/
private int threshold; // Default to 0
/**
* 將“調整大小閾值”設置爲在最壞情況下保持2/3的負載係數。
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
/**
* Increment i modulo len.
*/
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
/**
* Decrement i modulo len.
*/
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
/**
* 構造一個最初包含(firstKey,firstValue)的新映射。
* ThreadLocalMaps是按需地構建的,
* 只有當我們至少有一個條目要放進去時,纔會創建一個。
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
/**
* 構造一個新映射,其中包含來自給定父映射的所有可繼承線程局部變量。
* 僅由CreateInheriteMap調用。
*
* @param parentMap 與父線程關聯的映射。
*/
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
/**
* 獲取項。此方法本身只處理快速路徑:
* 現有key的直接命中。否則它將轉發到getEntryAfterMiss。
* 這是爲了最大限度地提高性能直接命中
*/
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
/**
* 在其直接哈希槽中找不到key時使用的getEntry方法的版本。
* @param key the thread local object
* @param i the table index for key's hash code
* @param e the entry at table[i]
* @return the entry associated with key, or null if no such
*/
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);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
/**
* 設置值。
* @param key the thread local object
* @param value the value to be set
*/
private void set(ThreadLocal<?> key, Object value) {
// We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
if (k == key) {
e.value = value;
return;
}
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
/**
* Remove the entry for key.
*/
private void remove(ThreadLocal<?> key) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
if (e.get() == key) {
e.clear();
expungeStaleEntry(i);
return;
}
}
}
/**
* 用指定鍵的項替換set操作期間遇到的過時項。
* @param key the key
* @param value the value to be associated with key
* @param staleSlot index of the first stale entry encountered while
* searching for key.
*/
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
// 備份以檢查當前運行中以前的陳舊條目。
// 我們一次清理整個運行,以避免由於垃圾收集器釋放
// 成束的ref(即每當收集器運行時)而導致持續的增量重新灰化。
int slotToExpunge = staleSlot;
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
// Find either the key or trailing null slot of run, whichever
// occurs first
for (int i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
// If we find key, then we need to swap it
// with the stale entry to maintain hash table order.
// The newly stale slot, or any other stale slot
// encountered above it, can then be sent to expungeStaleEntry
// to remove or rehash all of the other entries in run.
if (k == key) {
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
if (slotToExpunge == staleSlot)
slotToExpunge = i;
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}
// If we didn't find stale entry on backward scan, the
// first stale entry seen while scanning for key is the
// first still present in the run.
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
// If key not found, put new entry in stale slot
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
/**
* 刪除過時的entry
*/
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// 刪除staleSlot位置的entry
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// 重新hash直到tab[i]爲null
Entry e;
int i;
for (i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null;
tab[i] = null;
size--;
} else {
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
/**
* 試探性地掃描一些單元格以查找過時的條目
*/
private boolean cleanSomeSlots(int i, int n) {
boolean removed = false;
Entry[] tab = table;
int len = tab.length;
do {
i = nextIndex(i, len);
Entry e = tab[i];
if (e != null && e.get() == null) {
n = len;
removed = true;
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);
return removed;
}
/**
* 重新hash和或調整table的大小
*/
private void rehash() {
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
/**
* 容量增加一倍
*/
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null; // Help the GC
} else {
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
/**
* 刪除表中所有null值.
*/
private void expungeStaleEntries() {
Entry[] tab = table;
int len = tab.length;
for (int j = 0; j < len; j++) {
Entry e = tab[j];
if (e != null && e.get() == null)
expungeStaleEntry(j);
}
}
}
}
更多精彩內容請關注微信公衆號: