乾了這杯java之ThreadLocal

ThreadLocal

Java篇

  1. 是什麼
  2. 怎麼用
  3. 源碼
  4. 缺點
  5. 總結

是什麼

ThreadLocal是一個關於建立線程局部變量的類,這個變量只能當前線程使用,其餘線程不可用。
ThreadLocal提供get()和set()方法建立和修改變量。java

怎麼使用

ThreadLocal threadLocal = new ThreadLocal();
ThreadLocal<String> threadLocal = new ThreadLocal<>();
ThreadLocal threadLocal = new ThreadLocal<String>() {
    @Override
    protected String initialValue() {
        return "初始化值";
    }
};

源碼

類結構圖

get(),set()

查看ThreadLocal中的get(),set()中有一個ThreadLocalMap對象數組

//set 方法
public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

//get方法
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

ThreadLocalMap

ThreadLocalMap 就是一個內部靜態類,沒有繼承也沒有接口,是一個自定義的Hash映射,用戶維護線程局部變量。數據結構

static class ThreadLocalMap

ThreadLocalMap的內部類Entry,繼承WeakReference 弱引用

static class Entry extends WeakReference<ThreadLocal<?>> {
    Object value;

    Entry(ThreadLocal<?> k, Object v) {
        //key放在WeakReference<ThreadLocal<?>>中
        super(k);
          //變量放在Object value中
        value = v;
    }
}

ThreadLocalMap中存放線程局部變量的數據結構

private Entry[] table;

小結:

  1. ThreadLocal ——> ThreadLocalMap——> Entry[]
  2. Entry維護一個ThreadLocal 做爲key,value對應ThreadLocal的值

初始化方法

ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
     //默認容量爲16
    table = new Entry[INITIAL_CAPACITY];
      //threadLocalHashCode是一個原子類AtomicInteger的實例,每次調用會增長0x61c88647。&位移操做使存放分佈均勻
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
      //放入數組
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}

//nextHashCode實現
private final int threadLocalHashCode = nextHashCode();
private static AtomicInteger nextHashCode =
    new AtomicInteger();
private static final int HASH_INCREMENT = 0x61c88647;
private static int nextHashCode() {
    return nextHashCode.getAndAdd(HASH_INCREMENT);
}

小結:

  1. ThreadLocalMap默認容量爲16,每次計算索引位置會加0x61c88647而後和長度-1取模
  2. 索引是原子類

Entry的get

private Entry getEntry(ThreadLocal<?> key) {
      //定位i的位置
    int i = key.threadLocalHashCode & (table.length - 1);
    Entry e = table[i];
    if (e != null && e.get() == key)
        return e;
    else
        return getEntryAfterMiss(key, i, e);
}

private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
    Entry[] tab = table;
    int len = tab.length;
      //hashcode索引相同因此查找下一個,用循環比對取出
    while (e != null) {
        ThreadLocal<?> k = e.get();
        if (k == key)
            return e;
        if (k == null)
            expungeStaleEntry(i);
        else
            i = nextIndex(i, len);
        e = tab[i];
    }
    return null;
}

小結:

  1. get方法中先計算索引位置,若是key相同則返回,不一樣則用線性探測法取出,當key爲null的時候清理i所在位置直到不爲null的數據。若是找不到key的數據則返回null

Entry的Set

private void set(ThreadLocal<?> key, Object value) {
    Entry[] tab = table;
    int len = tab.length;
      //hashcode索引
    int i = key.threadLocalHashCode & (len-1);

      //線性探測法,若是在有值的狀況下,key不一樣則繼續下一個
    for (Entry e = tab[i];
         e != null;
         e = tab[i = nextIndex(i, len)]) {
        ThreadLocal<?> k = e.get();
          //若是當前有值&&key相同則更新value
        if (k == key) {
            e.value = value;
            return;
        }
         //若是key空,則key-value從新替換
        if (k == null) {
            replaceStaleEntry(key, value, i);
            return;
        }
    }
     //索引位置找到,插入key-value,對size+1
    tab[i] = new Entry(key, value);
    int sz = ++size;
      //cleanSomeSlots清理key關聯的對象被回收的數據,若是沒有被清理的&&size大於擴容因子,刷新
    if (!cleanSomeSlots(i, sz) && sz >= threshold)
        rehash();
}

小結:

1.計算索引位置
2.若是當前位置有值則索引+1判斷是否爲空,不爲空繼續+1,直到找到位置插入
3.size+1
4.是否清理key爲null的數據,若是沒有被清理&& size大於列表長度的2/3則擴容ide

清理key關聯的對象被回收的數據

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];
          //key爲null,被清理
        if (e != null && e.get() == null) {
            n = len;
            removed = true;
              //移除i位置以後爲key爲null的元素
            i = expungeStaleEntry(i);
        }
    } while ( (n >>>= 1) != 0);
    return removed;
}

expungeStaleEntry方法

private int expungeStaleEntry(int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;
      //將上面staleSlot的數據清空,大小減去1
    tab[staleSlot].value = null;
    tab[staleSlot] = null;
    size--;

    Entry e;
    int i;
      //以staleSlot日後找key爲null的
    for (i = nextIndex(staleSlot, len);
         (e = tab[i]) != null;
         i = nextIndex(i, len)) {
        ThreadLocal<?> k = e.get();
          //key爲null清空
        if (k == null) {
            e.value = null;
            tab[i] = null;
            size--;
        } else {
              //key不爲null,計算當前hashCode索引位置,若是不相同則把當前i清除,當前h位置不爲null,再向後查找key合適的索引
            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;
}

小結:

  1. 從staleSlot開始,清除key爲null的Entry,並將不爲空的元素放到合適的位置,最後遍歷到Entry爲空的元素時,跳出循環返回當前索引位置

rehash方法

private void rehash() {
    expungeStaleEntries(); //調用expungeStaleEntries()方法
      //size的長度超過容量的3/4,則擴容
    if (size >= threshold - threshold / 4)
        resize();
}

private void resize() {
    Entry[] oldTab = table;
    int oldLen = oldTab.length;
    int newLen = oldLen * 2;
    Entry[] newTab = new Entry[newLen];
    int count = 0;

    for (int j = 0; j < oldLen; ++j) {
        Entry e = oldTab[j];
        if (e != null) {
            ThreadLocal<?> k = e.get();
              //key爲null,value也設置爲null,清理
            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;
}

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

小結:

  1. 調用expungeStaleEntries方法,清理整個table中key爲null的Entry
  2. 若是清理後size超過閾值的1/2,則進行擴容。
  3. 新表長度爲老表2倍,建立新表。
  4. 遍歷老表全部元素,若是key爲null,將value清空;不然經過hash code計算新表的索引位置h,若是h已經有元素,則調用nextIndex方法直到尋找到空位置,將元素放在新表的對應位置。
  5. 設置新表擴容的閾值、更新size、table指向新表

缺點

內存泄露

從Entry源碼中能夠看出,Entry繼承了WeakReference弱引用,若是外部沒有引用ThreadLocal,則Entry中做爲Key的ThreadLocal會被銷燬成爲null,那麼它所對應的value不會被訪問到。當線程一直在執行&&沒有進行remove,rehash等操做時,value會一直存在內存,從而形成內存泄露this

總結

  1. Thread中都有一個ThreadLocalMap
  2. ThreadLocalMap的key是ThreadLocal實例
  3. 默認容量大小爲16,當size超過2/3容量&&沒被清理就rehash,
  4. 當size超過擴容因子3/4的時候擴容爲原來的2倍
  5. 當發現一個key爲null的時候,會進行清理,直到下一個key不爲null
  6. has衝突的解決方法和hashMap不相同,ThreadLocal是找這個衝突索引的下一個元素直到找到,hashMap是轉換爲紅黑樹
相關文章
相關標籤/搜索