亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

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

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java ThreadLocal用法實例詳解

發布時間:2020-08-30 18:08:28 來源:腳本之家 閱讀:188 作者:zkp_java 欄目:編程語言

本文實例講述了Java ThreadLocal用法。分享給大家供大家參考,具體如下:

目錄

  • ThreadLocal的基本使用
  • ThreadLocal實現原理
  • 源碼分析(基于openjdk11)
    • get方法:
      • setInitialValue方法
      • getEntry方法
    • set方法
      • ThreadLocalMap的set方法
        • replaceStaleEntry方法
        • cleanSomeSlots方法
        • rehash方法
        • expungeStaleEntries方法
        • resize方法

ThreadLocal實現了Java中線程局部變量。所謂線程局部變量就是保存在每個線程中獨有的一些數據,我們知道一個進程中的所有線程是共享該進程的資源的,線程對進程中的資源進行修改會反應到該進程中的其他線程上,如果我們希望一個線程對資源的修改不會影響到其他線程,那么就需要將該資源設為線程局部變量的形式。

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

      // 子線程中設置新值
      threadLocal1.set("new thread threadLocal1 value");
      threadLocal2.set("new thread threadLocal2 value");

      // 子線程打印出新值
      printThreadLocalInfo();

      System.out.println("================" + Thread.currentThread().getName() + " exit=================");
    });

    thread.start();
    // 等待新線程執行
    thread.join();
    
    // 在main線程打印threadLocal1和threadLocal2,驗證子線程對這兩個變量的修改是否會影響到main線程中的這兩個值
    printThreadLocalInfo();
    // 在main線程中給threadLocal1和threadLocal2設置新值
    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());
  }
}

運行結果如下:

================Thread-0 enter=================
Thread-0: threadLocal1 first value
Thread-0: threadLocal2 first value
Thread-0: new thread threadLocal1 value
Thread-0: new thread threadLocal2 value
================Thread-0 exit=================
main: threadLocal1 first value
main: threadLocal2 first value
main: main threadLocal1 value
main: main threadLocal2 value

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

ThreadLocal實現原理

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

源碼分析(基于openjdk11)

源碼包括ThreadLocalThreadLocalMapThreadLocalMapThreadLocal內定義的一個靜態內部類,用于存儲實際的數據。當調用ThreadLocalget或者set方法時都有可能創建當前線程的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
    // 對象對應的值
    if (map != null) {
    	// 從map中獲取當前ThreadLocal對象對應Entry對象
      ThreadLocalMap.Entry e = map.getEntry(this);
      if (e != null) {
      	// 獲取ThreadLocal對象對應的value值
        @SuppressWarnings("unchecked")
        T result = (T)e.value;
        return result;
      }
    }
    // threadLocals為null,則需要創建ThreadLocalMap對象并賦給
    // threadLocals,將當前ThreadLocal對象作為key,調用initialValue
    // 獲得的初始值作為value,放置到threadLocals的entry中;
    // 或者threadLocals不為null,但在threadLocals中未
    // 找到當前ThreadLocal對象對應的entry,則需要向threadLocals添加新的
    // entry,該entry以當前的ThreadLocal對象作為key,調用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對象對應的entry,則進入到setInitialValue方法;否則進入到ThreadLocalMapgetEntry方法。

setInitialValue方法

定義如下:

  private T setInitialValue() {
  	// 獲取初始值,如果我們在定義ThreadLocal對象時實現了ThreadLocal
  	// 的initialValue方法,就會調用我們自定義的方法來獲取初始值,否則
  	// 使用initialValue的默認實現返回null值
    T value = initialValue();
    Thread t = Thread.currentThread();
    // 獲取當前線程的threadLocals成員
    ThreadLocalMap map = getMap(t);
    if (map != null) {
    	// 若threadLocals存在則將ThreadLocal對象對應的value設置為初始值
      map.set(this, value);
    } else {
    	// 否則創建threadLocals對象并設置初始值
      createMap(t, value);
    }
    if (this instanceof TerminatingThreadLocal) {
      TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
    }
    return value;
  }

createMap方法實現

  /**
   * 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) {
  	// 創建一個ThreadLocalMap對象,用當前ThreadLocal對象和初始值value來
  	// 構造ThreadLocalMap中table的第一個entry。ThreadLocalMap對象賦
  	// 給線程的threadLocals成員
    t.threadLocals = new ThreadLocalMap(this, firstValue);
  }

ThreadLocalMap的構造方法定義如下:

    /**
     * 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) {
    	// 構造table數組,數組大小為INITIAL_CAPACITY
      table = new Entry[INITIAL_CAPACITY];
      // 計算key(ThreadLocal對象)在table中的索引
      int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
      // 用ThreadLocal對象和value來構造entry對象,并放到table的第i個位置
      table[i] = new Entry(firstKey, firstValue);
      size = 1;
      // 設置table的閾值,當table中元素個數超過該閾值時需要對table
      // 進行resize,通常在調用ThreadLocalMap的set方法時會發生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對象對應的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) {
    	// 根據ThreadLocal的hashcode計算該ThreadLocal對象在table中的位置
      int i = key.threadLocalHashCode & (table.length - 1);
      Entry e = table[i];
      // e為null則table不存在key對應的entry;
      // e.get() != key 可能是由于hash沖突導致key對應的entry在table
      // 的另外一個位置,需要繼續查找
      if (e != null && e.get() == key)
        return e;
      else
      	// e==null或者e.get() != key 繼續查找key對應的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 繼續往后尋找,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發生碰撞的概率:

    /**
     * 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中元素個數減一
      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則發生沖突,繼續尋找下一個位置
            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直接設置新值
    if (map != null) {
      map.set(this, value);
    } else {
    	// threadLocals為null則需要創建ThreadLocalMap對象并賦給
    	// Thread的threadLocals成員
      createMap(t, value);
    }
  }

createMap前面已經分析過,接下來分析ThreadLocalMap的set方法

ThreadLocalMap的set方法

ThreadLocalMap的set方法定義如下,將當前的ThreadLocal對象作為key,傳入的value為值,用key和value創建entry,放到table中適當的位置:

    /**
     * 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個位置已經存在有效的entry,需要繼續
			// 往后尋找新的位置
      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個數
      // 大于threshold,這進行rehash操作
      if (!cleanSomeSlots(i, sz) && sz >= threshold)
        rehash();
    }
replaceStaleEntry方法

replaceStaleEntry的作用是用set方法傳過來的key和value構造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;
    }

更多java相關內容感興趣的讀者可查看本站專題:《Java進程與線程操作技巧總結》、《Java數據結構與算法教程》、《Java操作DOM節點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》

希望本文所述對大家java程序設計有所幫助。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

东港市| 吉安市| 镇雄县| 鹤峰县| 隆安县| 莱阳市| 陈巴尔虎旗| 辽阳县| 饶平县| 宿迁市| 奉化市| 潞西市| 云安县| 哈密市| 和政县| 法库县| 呈贡县| 赫章县| 新闻| 景德镇市| 开远市| 关岭| 永年县| 乐陵市| 南召县| 开阳县| 神木县| 天气| 囊谦县| 湘阴县| 尤溪县| 平昌县| 株洲市| 清涧县| 高青县| 武夷山市| 瑞安市| 安宁市| 香河县| 开阳县| 济宁市|