Thread ThreadLocal ThreadLocalMap?蒙圈

先贊後看,養成習慣 🌹 歡迎微信關注[Java編程之道],天天進步一點點,沉澱技術分享知識。java

閒談ThreadLocal

前面在個人GitHub倉庫 V-LoggingTool 中有簡單的使用過ThreadLocal,主要用在了切面類中,功能上須要取到前置加強攔截到的用戶信息暫存,執行到後置加強時從該ThreadLocal中取出用戶信息並使用。git

今天我們就嘮嘮ThreadLocal的相關知識,瞭解一下他的數據結構、用法、原理等。我們層層深刻...github

看了網上很多關於ThreadLocal的講解,源碼比較簡單可是對於Thread、ThreadLocal、ThreadLocalMap的關係講的有點晦澀,尤爲是那張亙古不變的ThreadLocal的內部結構圖,額...我真的看了好久才明白是怎麼回事。編程

ThreadLocal工具類

ThreadLocal是一個本地線程副本變量工具類,主要用於將私有線程和該線程存放的副本對象作一個映射,各個線程之間的變量互不干擾。數組

官方說的仍是比較明白了,提煉關鍵字工具類,在我看來ThreadLocal就是提供給每一個線程操做變量的工具類,作到了線程之間的變量隔離目的bash

內部結構圖

接下來就是看圖說話:微信

  • 每一個Thread線程內部都有一個ThreadLocalMap。
  • Map裏面存儲線程本地對象ThreadLocal(key)和線程的變量副本(value)。
  • Thread內部的Map是由ThreadLocal維護,ThreadLocal負責向map獲取和設置線程的變量值。
  • 一個Thread能夠有多個ThreadLocal。

每一個線程都有其獨有的Map結構,而Map中存有的是ThreadLocal爲Key變量副本爲Vaule的鍵值對,以此達到變量隔離的目的。數據結構

平時是怎麼使用ThreadLocal的?less

package threadlocal;

/** * @Auther: Xianglei * @Company: Java編程之道 * @Date: 2020/7/2 21:44 * @Version 1.0 */
public class main {
    private static ThreadLocal<String> sThreadLocal = new ThreadLocal<>();
    public static void main(String args[]) {
        sThreadLocal.set("這是在主線程中");
        System.out.println("線程名字:" + Thread.currentThread().getName() + "---" + sThreadLocal.get());
        //線程a
        new Thread(new Runnable() {
            @Override
            public void run() {
                sThreadLocal.set("這是在線程a中");
                System.out.println("線程名字:" + Thread.currentThread().getName() + "---" + sThreadLocal.get());
            }
        }, "線程a").start();
        //線程b
        new Thread(new Runnable() {
            @Override
            public void run() {
                sThreadLocal.set("這是在線程b中");
                System.out.println("線程名字:" + Thread.currentThread().getName() + "---" + sThreadLocal.get());
            }
        }, "線程b").start();
        //線程c 
        new Thread(() -> {
            sThreadLocal.set("這是在線程c中");
            System.out.println("線程名字:" + Thread.currentThread().getName() + "---" + sThreadLocal.get());
        }, "線程c").start();
    }
}

複製代碼

輸出結果以下ide

線程名字:main---這是在主線程中
線程名字:線程b---這是在線程b中
線程名字:線程a---這是在線程a中
線程名字:線程c---這是在線程c中
Process finished with exit code 0
複製代碼

能夠看出每一個線程各經過ThreadLocal對本身ThreadLocalMap中的數據存取並無出現髒讀的現象。就是由於每一個線程內部已經存儲了ThreadLocal爲Key變量副本爲Vaule的鍵值對。(隔離了)

可能你有點懵,ThreadLocal是怎麼把變量複製到Thread的ThreadLocalMap中的?

我們接着嘮...

當咱們初始化一個線程的時候其內部幹去建立了一個ThreadLocalMap的Map容器待用。

public class Thread implements Runnable {
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
}
複製代碼

當ThreadLocalMap被建立加載的時候其靜態內部類Entry也隨之加載,完成初始化動做。

static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
       Object value;
        Entry(ThreadLocal<?> k, Object v) {
            super(k);
            value = v;
        }
}
複製代碼

到此,線程Thread內部的Map容器初始化完畢,那麼它又是如何和ThreadLocal纏上關係,ThreadLocal又是如何管理鍵值對的關係。

ThreadLocal探析

咱們就其核心方法分析一下內部的邏輯,同時解答上述存在的疑問:

  • set()方法用於保存當前線程的副本變量值。

  • get()方法用於獲取當前線程的副本變量值。

  • initialValue()爲當前線程初始副本變量值。

  • remove()方法移除當前線程的副本變量值。

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();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}
複製代碼

解說一下你就懂了:

當咱們在Thread內部調用set方法時:

  • 第一步會去獲取調用當前方法的線程Thread
  • 而後順其天然的拿到當前線程內部ThreadLocalMap容器。
  • 最後就把變量副本給丟進去。

沒了...懂了嗎,ThreadLocal(就認爲是個維護線程內部變量的工具!)只是在Set的時候去操做了Thread內部的·ThreadLocalMap將變量拷貝到了Thread內部的Map容器中,Key就是當前的ThreadLocal,Value就是變量的副本。

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();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null)
            return (T)e.value;
    }
    return setInitialValue();
}

ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

private T setInitialValue() {
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

protected T initialValue() {
    return null;
}
複製代碼
  • 獲取當前線程的ThreadLocalMap對象
  • 從map中根據this(當前的threadlocal對象)獲取線程存儲的Entry節點。
  • 從Entry節點獲取存儲的對應Value副本值返回。
  • map爲空的話返回初始值null,即線程變量副本爲null。

remove方法

清除Map中的KV

/** * Removes the current thread's value for this thread-local * variable. If this thread-local variable is subsequently * {@linkplain #get read} by the current thread, its value will be * reinitialized by invoking its {@link #initialValue} method, * unless its value is {@linkplain #set set} by the current thread * in the interim. This may result in multiple invocations of the * <tt>initialValue</tt> method in the current thread. * * @since 1.5 */
public void remove() {
 ThreadLocalMap m = getMap(Thread.currentThread());
 if (m != null)
     m.remove(this);
}

ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

 /** * 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;
              }
          }
    }
複製代碼

下面再認識一下ThreadLocalMap,一個真正存儲(隔離)數據的東西。

ThreadLocalMap

ThreadLocalMap是ThreadLocal的內部類,實現了一套本身的Map結構,我們看一下內部的繼承關係就一目瞭然。

其Entry使用的是K-V方式來組織數據,Entry中key是ThreadLocal對象,且是一個弱引用(弱引用,生命週期只能存活到下次GC前)。

對於弱引用引起的問題咱們最後再說

static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
         Object value;

         Entry(ThreadLocal<?> k, Object v) {
            super(k);
            value = v;
        }
 }
複製代碼

ThreadLocalMap的成員變量

static class ThreadLocalMap {
    /** * The initial capacity -- MUST be a power of two. */
    private static final int INITIAL_CAPACITY = 16;

    /** * The table, resized as necessary. * table.length MUST always be a power of two. */
    private Entry[] table;

    /** * The number of entries in the table. */
    private int size = 0;

    /** * The next size value at which to resize. */
    private int threshold; // Default to 0
}
複製代碼

HashCode 計算

ThreaLocalMap中沒有采用傳統的調用ThreadLocal的hashcode方法(繼承自object的hashcode),而是調用nexthashcode,源碼以下:

private final int threadLocalHashCode = nextHashCode();
private static AtomicInteger nextHashCode = new AtomicInteger();
 //1640531527 可以讓hash槽位分佈至關均勻
private static final int HASH_INCREMENT = 0x61c88647; 
private static int nextHashCode() {
      return nextHashCode.getAndAdd(HASH_INCREMENT);
}
複製代碼

Hash衝突

和HashMap的最大的不一樣在於,ThreadLocalMap解決Hash衝突的方式就是簡單的步長加1或減1及線性探測,尋找下一個相鄰的位置。

/** * 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);
}
複製代碼

ThreadLocalMap採用線性探測的方式解決Hash衝突的效率很低,若有大量不一樣的ThreadLocal對象放入map中時發送衝突。因此建議每一個線程只存一個變量(一個ThreadLocal)就不存在Hash衝突的問題,若是一個線程要保存set多個變量,就須要建立多個ThreadLocal,多個ThreadLocal放入Map中時會極大的增長Hash衝突的可能。

清楚意思嗎?當你在一個線程須要保存多個變量時,你覺得是屢次set?你錯了你得建立多個ThreadLocal,屢次set的達不到存儲多個變量的目的。

sThreadLocal.set("這是在線程a中");
複製代碼

Key的弱引用問題

看看官話,爲何要用弱引用。

To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys.
爲了處理很是大生命週期很是長的線程,哈希表使用弱引用做爲 key。

  • 生命週期長:暫時能夠想到線程池中的線程

ThreadLocal在沒有外部對象強引用時如Thread,發生GC時弱引用Key會被回收,而Value是強引用不會回收,若是建立ThreadLocal的線程一直持續運行如線程池中的線程,那麼這個Entry對象中的value就有可能一直得不到回收,發生內存泄露。

  • key 若是使用強引用:引用的ThreadLocal的對象被回收了,可是ThreadLocalMap還持有ThreadLocal的強引用,若是沒有手動刪除,ThreadLocal不會被回收,致使Entry內存泄漏。

  • key 使用弱引用:引用的ThreadLocal的對象被回收了,因爲ThreadLocalMap持有ThreadLocal的弱引用,即便沒有手動刪除,ThreadLocal也會被回收。value在下一次ThreadLocalMap調用set,get,remove的時候會被清除。

Java8中已經作了一些優化如,在ThreadLocal的get()、set()、remove()方法調用的時候會清除掉線程ThreadLocalMap中全部Entry中Key爲null的Value,並將整個Entry設置爲null,利於下次內存回收。

Java8中for循環遍歷整個Entry數組,遇到key=null的就會替換從而避免內存泄露的問題。

private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter 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;
        }
複製代碼

一般ThreadLocalMap的生命週期跟Thread(注意線程池中的Thread)同樣長,若是沒有手動刪除對應key(線程使用結束歸還給線程池了,其中的KV再也不被使用但又不會GC回收,可認爲是內存泄漏),必定會致使內存泄漏,可是使用弱引用能夠多一層保障:弱引用ThreadLocal會被GC回收,不會內存泄漏,對應的value在下一次ThreadLocalMap調用set,get,remove的時候會被清除,Java8已經作了上面的代碼優化。

總結

  • 每一個ThreadLocal只能保存一個變量副本,若是想要一個線程可以保存多個副本以上,就須要建立多個ThreadLocal。
  • ThreadLocal內部的ThreadLocalMap鍵爲弱引用,會有內存泄漏的風險。
  • 每次使用完ThreadLocal,都調用它的remove()方法,清除數據。
相關文章
相關標籤/搜索