中文字幕日韩精品一区二区免费_精品一区二区三区国产精品无卡在_国精品无码专区一区二区三区_国产αv三级中文在线

JavaThreadLocal用法的實例分析

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的基本使用

如下示例所示,定義兩個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

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

ThreadLocal實現(xiàn)原理

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

源碼分析(基于openjdk11)

源碼包括ThreadLocalThreadLocalMap,ThreadLocalMapThreadLocal內(nèi)定義的一個靜態(tài)內(nèi)部類,用于存儲實際的數(shù)據(jù)。當調(diào)用ThreadLocalget或者set方法時都有可能創(chuà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() {  

// 獲取當前線程    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;  }

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

setInitialValue方法

定義如下:

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中的索引。

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計算該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;    }

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

// 獲取當前線程的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方法

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

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

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用法的實例分析問題的解答就分享到這里了,希望以上內(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)

網(wǎng)站優(yōu)化排名
辽阳市| 宜君县| 临高县| 土默特左旗| 宿州市| 苏州市| 博兴县| 博乐市| 德令哈市| 普洱| 建湖县| 兴业县| 绿春县| 彭山县| 安乡县| 通河县| 德保县| 图木舒克市| 山西省| 杭州市| 广州市| 宝应县| 武乡县| 民丰县| 二手房| 汾阳市| 集贤县| 宝山区| 防城港市| 汉源县| 织金县| 宁国市| 北京市| 电白县| 扎兰屯市| 惠安县| 凤冈县| 罗甸县| 深州市| 屯留县| 榆林市|