溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JavaThreadLocal用法的實(shí)例分析

發(fā)布時(shí)間:2021-12-17 15:43:14 來源:億速云 閱讀:138 作者:柒染 欄目:編程語言

JavaThreadLocal用法的實(shí)例分析,針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。

ThreadLocal實(shí)現(xiàn)了Java中線程局部變量。所謂線程局部變量就是保存在每個(gè)線程中獨(dú)有的一些數(shù)據(jù),我們知道一個(gè)進(jìn)程中的所有線程是共享該進(jìn)程的資源的,線程對(duì)進(jìn)程中的資源進(jìn)行修改會(huì)反應(yīng)到該進(jìn)程中的其他線程上,如果我們希望一個(gè)線程對(duì)資源的修改不會(huì)影響到其他線程,那么就需要將該資源設(shè)為線程局部變量的形式。

ThreadLocal的基本使用

如下示例所示,定義兩個(gè)ThreadLocal變量,然后分別在主線程和子線程中對(duì)線程局部變量進(jìn)行修改,然后分別獲取線程局部變量的值:

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,驗(yàn)證子線程對(duì)這兩個(gè)變量的修改是否會(huì)影響到main線程中的這兩個(gè)值    printThreadLocalInfo();    

// 在main線程中給threadLocal1和threadLocal2設(shè)置新值    threadLocal1.set("main threadLocal1 value");    threadLocal2.set("main threadLocal2 value");    

// 驗(yàn)證main線程中這兩個(gè)變量是否為新值    printThreadLocalInfo();  }  private static void printThreadLocalInfo() {    System.out.println(Thread.currentThread().getName() + ": " + threadLocal1.get());    System.out.println(Thread.currentThread().getName() + ": " + threadLocal2.get());  }}

運(yùn)行結(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

如果子線程對(duì)threadLocal1threadLocal2的修改會(huì)影響到main線程中的threadLocal1threadLocal2,那么在main線程第一次printThreadLocalInfo();打印出的應(yīng)該是修改后的新值,即為new thread threadLocal1 valuenew thread threadLocal2 value和,但實(shí)際打印結(jié)果并不是這樣,說明在新線程中對(duì)threadLocal1threadLocal2的修改并不會(huì)影響到main線程中的這兩個(gè)變量,似乎main線程中的threadLocal1threadLocal2作用域僅局限于main線程,新線程中的threadLocal1threadLocal2作用域僅局限于新線程,這就是線程局部變量的由來。

ThreadLocal實(shí)現(xiàn)原理

如下圖所示每個(gè)線程對(duì)象里會(huì)持有一個(gè)java.lang.ThreadLocal.ThreadLocalMap類型的threadLocals成員變量,而ThreadLocalMap里有一個(gè)java.lang.ThreadLocal.ThreadLocalMap.Entry[]類型的table成員,這是一個(gè)數(shù)組,數(shù)組元素是Entry類型,Entry中相當(dāng)于有一個(gè)keyvalue,key指向所有線程共享的java.lang.ThreadLocal對(duì)象,value指向各線程私有的變量,這樣保證了線程局部變量的隔離性,每個(gè)線程只是讀取和修改自己所持有的那個(gè)value對(duì)象,相互之間沒有影響。

源碼分析(基于openjdk11)

源碼包括ThreadLocalThreadLocalMap,ThreadLocalMapThreadLocal內(nèi)定義的一個(gè)靜態(tài)內(nèi)部類,用于存儲(chǔ)實(shí)際的數(shù)據(jù)。當(dāng)調(diào)用ThreadLocalget或者set方法時(shí)都有可能創(chuàng)建當(dāng)前線程的threadLocals成員(ThreadLocalMap類型)。

get方法:

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() {  

// 獲取當(dāng)前線程    Thread t = Thread.currentThread();   

 // 獲取當(dāng)前線程的threadLocals成員變量,這是一個(gè)ThreadLocalMap    ThreadLocalMap map = getMap(t);    

// threadLocals不為null則直接從threadLocals中取出ThreadLocal    

// 對(duì)象對(duì)應(yīng)的值    if (map != null) {    

// 從map中獲取當(dāng)前ThreadLocal對(duì)象對(duì)應(yīng)Entry對(duì)象      ThreadLocalMap.Entry e = map.getEntry(this);     

 if (e != null) {      

// 獲取ThreadLocal對(duì)象對(duì)應(yīng)的value值        @SuppressWarnings("unchecked")        T result = (T)e.value;        return result;      }    }    

// threadLocals為null,則需要?jiǎng)?chuàng)建ThreadLocalMap對(duì)象并賦給    

// threadLocals,將當(dāng)前ThreadLocal對(duì)象作為key,調(diào)用initialValue    

// 獲得的初始值作為value,放置到threadLocals的entry中;    

// 或者threadLocals不為null,但在threadLocals中未    

// 找到當(dāng)前ThreadLocal對(duì)象對(duì)應(yīng)的entry,則需要向threadLocals添加新的    

// entry,該entry以當(dāng)前的ThreadLocal對(duì)象作為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;  }

當(dāng)ThreadthreadLocals為null,或者在ThreadthreadLocals中未找到當(dāng)前ThreadLocal對(duì)象對(duì)應(yīng)的entry,則進(jìn)入到setInitialValue方法;否則進(jìn)入到ThreadLocalMapgetEntry方法。

setInitialValue方法

定義如下:

private T setInitialValue() {  // 獲取初始值,如果我們?cè)诙xThreadLocal對(duì)象時(shí)實(shí)現(xiàn)了ThreadLocal  // 的initialValue方法,就會(huì)調(diào)用我們自定義的方法來獲取初始值,否則  // 使用initialValue的默認(rèn)實(shí)現(xiàn)返回null值    T value = initialValue();    Thread t = Thread.currentThread();    // 獲取當(dāng)前線程的threadLocals成員    ThreadLocalMap map = getMap(t);    if (map != null) {    // 若threadLocals存在則將ThreadLocal對(duì)象對(duì)應(yīng)的value設(shè)置為初始值      map.set(this, value);    } else {    // 否則創(chuàng)建threadLocals對(duì)象并設(shè)置初始值      createMap(t, value);    }    if (this instanceof TerminatingThreadLocal) {      TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);    }    return value;  }

createMap方法實(shí)現(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)建一個(gè)ThreadLocalMap對(duì)象,用當(dāng)前ThreadLocal對(duì)象和初始值value來  

// 構(gòu)造ThreadLocalMap中table的第一個(gè)entry。ThreadLocalMap對(duì)象賦  

// 給線程的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];      

// 計(jì)算key(ThreadLocal對(duì)象)在table中的索引      int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);      

// 用ThreadLocal對(duì)象和value來構(gòu)造entry對(duì)象,并放到table的第i個(gè)位置      table[i] = new Entry(firstKey, firstValue);      size = 1;      

// 設(shè)置table的閾值,當(dāng)table中元素個(gè)數(shù)超過該閾值時(shí)需要對(duì)table     

 // 進(jìn)行resize,通常在調(diào)用ThreadLocalMap的set方法時(shí)會(huì)發(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中定義的一個(gè)hashcode,使用該hashcode進(jìn)行hash運(yùn)算從而找到該ThreadLocal對(duì)象對(duì)應(yīng)的entry在table中的索引。

getEntry方法

定義如下:

/**     * 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計(jì)算該ThreadLocal對(duì)象在table中的位置      int i = key.threadLocalHashCode & (table.length - 1);      Entry e = table[i];      

// e為null則table不存在key對(duì)應(yīng)的entry;      

// e.get() != key 可能是由于hash沖突導(dǎo)致key對(duì)應(yīng)的entry在table      

// 的另外一個(gè)位置,需要繼續(xù)查找      if (e != null && e.get() == key)        return e;      else      

// e==null或者e.get() != key 繼續(xù)查找key對(duì)應(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個(gè)位置一直往后找,直到找到鍵為key的entry為止      while (e != null) {        

ThreadLocal<?> k = e.get();        

// 若k==key,則找到了entry        if (k == key)          return e;        

// k == null 需要?jiǎng)h除該entry        if (k == null)          expungeStaleEntry(i);        

// k != key && k != null 繼續(xù)往后尋找,nextIndex就是取(i+1)        

// 即table中第(i+1)個(gè)位置的entry        else          i = nextIndex(i, len);        e = tab[i];      }      return null;    }

expungeStaleEntry方法刪除key為null的entry,刪除后對(duì)staleSlot位置的entry和其后第一個(gè)為null的entry之間的entry進(jìn)行一個(gè)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中元素個(gè)數(shù)減一      size--;      

// Rehash until we encounter null      

// 將table中staleSlot處entry和下一個(gè)為null的entry之間的      

// entry重新進(jìn)行hash放置到新的位置     

 // 遇到的entry的key為null則刪除該entry      Entry e;      int i;      for (i = nextIndex(staleSlot, len);         (e = tab[i]) != null;         i = nextIndex(i, len)) {       

 // e是下一個(gè)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ù)尋找下一個(gè)位置            while (tab[h] != null)              h = nextIndex(h, len);            tab[h] = e;          }        }      }      return i;    }

set方法

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();    

// 獲取當(dāng)前線程的threadLocals    ThreadLocalMap map = getMap(t);    

// threadLocals不為null直接設(shè)置新值    if (map != null) {      map.set(this, value);    } else {    

// threadLocals為null則需要?jiǎng)?chuàng)建ThreadLocalMap對(duì)象并賦給    

// Thread的threadLocals成員      createMap(t, value);    }  }

createMap前面已經(jīng)分析過,接下來分析ThreadLocalMap的set方法

ThreadLocalMap的set方法

ThreadLocalMap的set方法定義如下,將當(dāng)前的ThreadLocal對(duì)象作為key,傳入的value為值,用key和value創(chuàng)建entry,放到table中適當(dāng)?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計(jì)算entry在table中的位置      int i = key.threadLocalHashCode & (len-1);// tab[i]不為null的話,則第i個(gè)位置已經(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;        }      }

// 此時(shí)第i個(gè)位置entry為null,將新entry放置到這個(gè)位置     

 tab[i] = new Entry(key, value);      

int sz = ++size;     

 // 試圖清除無效的entry,若清除失敗并且table中有效entry個(gè)數(shù)     

 // 大于threshold,這進(jìn)行rehash操作      

if (!cleanSomeSlots(i, sz) && sz >= threshold)        rehash();

    }

replaceStaleEntry方法

replaceStaleEntry的作用是用set方法傳過來的key和value構(gòu)造entry,將這個(gè)entry放到staleSlot后面的某個(gè)位置:

/**     * 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往前找到第一個(gè)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個(gè)位置,此時(shí)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并進(jìn)行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);    }

以下源碼只可意會(huì),不可言傳…不再做說明

cleanSomeSlots方法

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方法

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方法

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方法

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用法的實(shí)例分析問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI