JavaThreadLocal用法的實例分析,針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
成都創(chuàng)新互聯(lián)公司主營工農(nóng)網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都App定制開發(fā),工農(nóng)h5微信小程序定制開發(fā)搭建,工農(nóng)網(wǎng)站營銷推廣歡迎工農(nóng)等地區(qū)企業(yè)咨詢
ThreadLocal實現(xiàn)了Java中線程局部變量。所謂線程局部變量就是保存在每個線程中獨有的一些數(shù)據(jù),我們知道一個進程中的所有線程是共享該進程的資源的,線程對進程中的資源進行修改會反應(yīng)到該進程中的其他線程上,如果我們希望一個線程對資源的修改不會影響到其他線程,那么就需要將該資源設(shè)為線程局部變量的形式。
如下示例所示,定義兩個ThreadLocal變量,然后分別在主線程和子線程中對線程局部變量進行修改,然后分別獲取線程局部變量的值:
public class ThreadLocalTest { private static ThreadLocal<String> threadLocal1 = ThreadLocal.withInitial(() -> "threadLocal1 first value"); private static ThreadLocal<String> threadLocal2 = ThreadLocal.withInitial(() -> "threadLocal2 first value"); public static void main(String[] args) throws Exception{ Thread thread = new Thread(() -> { System.out.println("================" + Thread.currentThread().getName() + " enter=================");
// 子線程中打印出初始值 printThreadLocalInfo();
// 子線程中設(shè)置新值 threadLocal1.set("new thread threadLocal1 value"); threadLocal2.set("new thread threadLocal2 value");
// 子線程打印出新值 printThreadLocalInfo(); System.out.println("================" + Thread.currentThread().getName() + " exit================="); }); thread.start();
// 等待新線程執(zhí)行 thread.join();
// 在main線程打印threadLocal1和threadLocal2,驗證子線程對這兩個變量的修改是否會影響到main線程中的這兩個值 printThreadLocalInfo();
// 在main線程中給threadLocal1和threadLocal2設(shè)置新值 threadLocal1.set("main threadLocal1 value"); threadLocal2.set("main threadLocal2 value");
// 驗證main線程中這兩個變量是否為新值 printThreadLocalInfo(); } private static void printThreadLocalInfo() { System.out.println(Thread.currentThread().getName() + ": " + threadLocal1.get()); System.out.println(Thread.currentThread().getName() + ": " + threadLocal2.get()); }}
運行結(jié)果如下:
================Thread-0 enter=================Thread-0: threadLocal1 first valueThread-0: threadLocal2 first valueThread-0: new thread threadLocal1 valueThread-0: new thread threadLocal2 value================Thread-0 exit=================main: threadLocal1 first valuemain: threadLocal2 first valuemain: main threadLocal1 valuemain: main threadLocal2 value
如果子線程對threadLocal1
和threadLocal2
的修改會影響到main線程中的threadLocal1
和threadLocal2
,那么在main線程第一次printThreadLocalInfo();
打印出的應(yīng)該是修改后的新值,即為new thread threadLocal1 value
和new thread threadLocal2 value
和,但實際打印結(jié)果并不是這樣,說明在新線程中對threadLocal1
和threadLocal2
的修改并不會影響到main線程中的這兩個變量,似乎main線程中的threadLocal1
和threadLocal2
作用域僅局限于main線程,新線程中的threadLocal1
和threadLocal2
作用域僅局限于新線程,這就是線程局部變量的由來。
如下圖所示每個線程對象里會持有一個java.lang.ThreadLocal.ThreadLocalMap
類型的threadLocals
成員變量,而ThreadLocalMap
里有一個java.lang.ThreadLocal.ThreadLocalMap.Entry[]
類型的table
成員,這是一個數(shù)組,數(shù)組元素是Entry
類型,Entry
中相當于有一個key
和value
,key
指向所有線程共享的java.lang.ThreadLocal
對象,value
指向各線程私有的變量,這樣保證了線程局部變量的隔離性,每個線程只是讀取和修改自己所持有的那個value對象,相互之間沒有影響。
源碼包括ThreadLocal
和ThreadLocalMap
,ThreadLocalMap
是ThreadLocal
內(nèi)定義的一個靜態(tài)內(nèi)部類,用于存儲實際的數(shù)據(jù)。當調(diào)用ThreadLocal
的get
或者set
方法時都有可能創(chuàng)建當前線程的threadLocals
成員(ThreadLocalMap
類型)。
ThreadLocal的get方法定義如下
/** * Returns the value in the current thread's copy of this * thread-local variable. If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * * @return the current thread's value of this thread-local */ public T get() {
// 獲取當前線程 Thread t = Thread.currentThread();
// 獲取當前線程的threadLocals成員變量,這是一個ThreadLocalMap ThreadLocalMap map = getMap(t);
// threadLocals不為null則直接從threadLocals中取出ThreadLocal
// 對象對應(yīng)的值 if (map != null) {
// 從map中獲取當前ThreadLocal對象對應(yīng)Entry對象 ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
// 獲取ThreadLocal對象對應(yīng)的value值 @SuppressWarnings("unchecked") T result = (T)e.value; return result; } }
// threadLocals為null,則需要創(chuàng)建ThreadLocalMap對象并賦給
// threadLocals,將當前ThreadLocal對象作為key,調(diào)用initialValue
// 獲得的初始值作為value,放置到threadLocals的entry中;
// 或者threadLocals不為null,但在threadLocals中未
// 找到當前ThreadLocal對象對應(yīng)的entry,則需要向threadLocals添加新的
// entry,該entry以當前的ThreadLocal對象作為key,調(diào)用initialValue
// 獲得的值作為value return setInitialValue(); }
/** * Get the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @return the map */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
當Thread
的threadLocals
為null,或者在Thread
的threadLocals
中未找到當前ThreadLocal對象對應(yīng)的entry,則進入到setInitialValue
方法;否則進入到ThreadLocalMap
的getEntry
方法。
定義如下:
private T setInitialValue() { // 獲取初始值,如果我們在定義ThreadLocal對象時實現(xiàn)了ThreadLocal // 的initialValue方法,就會調(diào)用我們自定義的方法來獲取初始值,否則 // 使用initialValue的默認實現(xiàn)返回null值 T value = initialValue(); Thread t = Thread.currentThread(); // 獲取當前線程的threadLocals成員 ThreadLocalMap map = getMap(t); if (map != null) { // 若threadLocals存在則將ThreadLocal對象對應(yīng)的value設(shè)置為初始值 map.set(this, value); } else { // 否則創(chuàng)建threadLocals對象并設(shè)置初始值 createMap(t, value); } if (this instanceof TerminatingThreadLocal) { TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this); } return value; }
createMap
方法實現(xiàn)
/** * Create the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @param firstValue value for the initial entry of the map
*/ void createMap(Thread t, T firstValue) {
// 創(chuàng)建一個ThreadLocalMap對象,用當前ThreadLocal對象和初始值value來
// 構(gòu)造ThreadLocalMap中table的第一個entry。ThreadLocalMap對象賦
// 給線程的threadLocals成員 t.threadLocals = new ThreadLocalMap(this, firstValue); }
ThreadLocalMap
的構(gòu)造方法定義如下:
/** * Construct a new map initially containing (firstKey, firstValue). * ThreadLocalMaps are constructed lazily, so we only create * one when we have at least one entry to put in it. */ ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
// 構(gòu)造table數(shù)組,數(shù)組大小為INITIAL_CAPACITY table = new Entry[INITIAL_CAPACITY];
// 計算key(ThreadLocal對象)在table中的索引 int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
// 用ThreadLocal對象和value來構(gòu)造entry對象,并放到table的第i個位置 table[i] = new Entry(firstKey, firstValue); size = 1;
// 設(shè)置table的閾值,當table中元素個數(shù)超過該閾值時需要對table
// 進行resize,通常在調(diào)用ThreadLocalMap的set方法時會發(fā)生resize setThreshold(INITIAL_CAPACITY); }
/** * Set the resize threshold to maintain at worst a 2/3 load factor. */ private void setThreshold(int len) { threshold = len * 2 / 3; }
這里firstKey.threadLocalHashCode
是ThreadLocal中定義的一個hashcode,使用該hashcode進行hash運算從而找到該ThreadLocal對象對應(yīng)的entry在table中的索引。
定義如下:
/** * 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) {
// 根據(jù)ThreadLocal的hashcode計算該ThreadLocal對象在table中的位置 int i = key.threadLocalHashCode & (table.length - 1); Entry e = table[i];
// e為null則table不存在key對應(yīng)的entry;
// e.get() != key 可能是由于hash沖突導(dǎo)致key對應(yīng)的entry在table
// 的另外一個位置,需要繼續(xù)查找 if (e != null && e.get() == key) return e; else
// e==null或者e.get() != key 繼續(xù)查找key對應(yīng)的entry return getEntryAfterMiss(key, i, e); }
getEntryAfterMiss
方法定義如下:
/** * Version of getEntry method for use when key is not found in * its direct hash slot. * * @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;
// 從table的第i個位置一直往后找,直到找到鍵為key的entry為止 while (e != null) {
ThreadLocal<?> k = e.get();
// 若k==key,則找到了entry if (k == key) return e;
// k == null 需要刪除該entry if (k == null) expungeStaleEntry(i);
// k != key && k != null 繼續(xù)往后尋找,nextIndex就是取(i+1)
// 即table中第(i+1)個位置的entry else i = nextIndex(i, len); e = tab[i]; } return null; }
expungeStaleEntry
方法刪除key為null的entry,刪除后對staleSlot位置的entry和其后第一個為null的entry之間的entry進行一個rehash操作,rehash的目的是降低table發(fā)生碰撞的概率:
/** * Expunge a stale entry by rehashing any possibly colliding entries * lying between staleSlot and the next null slot. This also expunges * any other stale entries encountered before the trailing null. See * Knuth, Section 6.4 * * @param staleSlot index of slot known to have null key * @return the index of the next null slot after staleSlot * (all between staleSlot and this slot will have been checked * for expunging). */ private int expungeStaleEntry(int staleSlot) { Entry[] tab = table; int len = tab.length;
// expunge entry at staleSlot
// 刪除staleSlot位置的entry tab[staleSlot].value = null; tab[staleSlot] = null;
// table中元素個數(shù)減一 size--;
// Rehash until we encounter null
// 將table中staleSlot處entry和下一個為null的entry之間的
// entry重新進行hash放置到新的位置
// 遇到的entry的key為null則刪除該entry Entry e; int i; for (i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) {
// e是下一個entry ThreadLocal<?> k = e.get(); if (k == null) {
// 若entry的key為null,則刪除 e.value = null; tab[i] = null; size--; } else {
// entry的key不為null,需要將entry放到新的位置 int h = k.threadLocalHashCode & (len - 1); if (h != i) { tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
// tab[h]不為null則發(fā)生沖突,繼續(xù)尋找下一個位置 while (tab[h] != null) h = nextIndex(h, len); tab[h] = e; } } } return i; }
ThreadLocal的set方法定義如下:
/** * Sets the current thread's copy of this thread-local variable * to the specified value. Most subclasses will have no need to * override this method, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current thread's copy of * this thread-local. */ public void set(T value) { Thread t = Thread.currentThread();
// 獲取當前線程的threadLocals ThreadLocalMap map = getMap(t);
// threadLocals不為null直接設(shè)置新值 if (map != null) { map.set(this, value); } else {
// threadLocals為null則需要創(chuàng)建ThreadLocalMap對象并賦給
// Thread的threadLocals成員 createMap(t, value); } }
createMap
前面已經(jīng)分析過,接下來分析ThreadLocalMap的set
方法
ThreadLocalMap的set方法定義如下,將當前的ThreadLocal對象作為key,傳入的value為值,用key和value創(chuàng)建entry,放到table中適當?shù)奈恢茫?/p>
/** * Set the value associated with key. * * @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;
// 用key計算entry在table中的位置 int i = key.threadLocalHashCode & (len-1);// tab[i]不為null的話,則第i個位置已經(jīng)存在有效的entry,需要繼續(xù)// 往后尋找新的位置 for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
// 找到與key相同的entry,直接更新value的值
if (k == key) { e.value = value;
return; }
// 遇到key為null的entry,刪除該entry
if (k == null) { replaceStaleEntry(key, value, i);
return; } }
// 此時第i個位置entry為null,將新entry放置到這個位置
tab[i] = new Entry(key, value);
int sz = ++size;
// 試圖清除無效的entry,若清除失敗并且table中有效entry個數(shù)
// 大于threshold,這進行rehash操作
if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash();
}
replaceStaleEntry
的作用是用set方法傳過來的key和value構(gòu)造entry,將這個entry放到staleSlot后面的某個位置:
/** * Replace a stale entry encountered during a set operation * with an entry for the specified key. The value passed in * the value parameter is stored in the entry, whether or not * an entry already exists for the specified key. * * As a side effect, this method expunges all stale entries in the * "run" containing the stale entry. (A run is a sequence of entries * between two null slots.) * * @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;
// Back up to check for prior stale entry in current run.
// We clean out whole runs at a time to avoid continual
// incremental rehashing due to garbage collector freeing
// up refs in bunches (i.e., whenever the collector runs).
// 從staleSlot往前找到第一個key為null的entry的位置 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
// 從staleSlot位置往后尋找 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. // 若k與key相同,則直接更新value if (k == key) { e.value = value;// 將原來staleSlot位置的entry放置到第i個位置,此時tab[i]處的entry的key為null tab[i] = tab[staleSlot]; tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
// 從staleSlot處往前未找到key為null的entry if (slotToExpunge == staleSlot)
// tab[i]處entry的key為null,也即tab[slotToExpunge]處entry的key為null slotToExpunge = i;
// 清除slotToExpunge位置的entry并進行rehash操作..... 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); }
以下源碼只可意會,不可言傳…不再做說明
cleanSomeSlots
方法:
/** * Heuristically scan some cells looking for stale entries.
* This is invoked when either a new element is added, or
* another stale one has been expunged. It performs a
* logarithmic number of scans, as a balance between no
* scanning (fast but retains garbage) and a number of scans
* proportional to number of elements, that would find all
* garbage but would cause some insertions to take O(n) time.
* * @param i a position known NOT to hold a stale entry. The
* scan starts at the element after i.
* * @param n scan control: {@code log2(n)} cells are scanned,
* unless a stale entry is found, in which case
* {@code log2(table.length)-1} additional cells are scanned.
* When called from insertions, this parameter is the number
* of elements, but when from replaceStaleEntry, it is the
* table length. (Note: all this could be changed to be either
* more or less aggressive by weighting n instead of just
* using straight log n. But this version is simple, fast, and
* seems to work well.)
* * @return true if any stale entries have been removed.
*/ 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; }
rehash
方法:
/** * Re-pack and/or re-size the table. First scan the entire * table removing stale entries. If this doesn't sufficiently * shrink the size of the table, double the table size. */ private void rehash() { expungeStaleEntries(); // Use lower threshold for doubling to avoid hysteresis if (size >= threshold - threshold / 4) resize(); }
expungeStaleEntries
方法:
/** * Expunge all stale entries in the table. */
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);
}
}
resize
方法:
/** * Double the capacity of the table. */
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (Entry e : oldTab) {
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;
}adLocal
關(guān)于JavaThreadLocal用法的實例分析問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。
網(wǎng)頁名稱:JavaThreadLocal用法的實例分析
URL鏈接:http://www.rwnh.cn/article24/ippsje.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、微信小程序、品牌網(wǎng)站設(shè)計、關(guān)鍵詞優(yōu)化、網(wǎng)站改版、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)