ThreadLocal源碼簡析

get和set方法的關鍵代碼以下:this

Thread t = Thread.currentThread(); 獲取當前線程對象線程

ThreadLocalMap map = getMap(t); 當前線程都有ThreadLocalMap這個對象的引用對象

ThreadLocalMap.Entry e = map.getEntry(this); 以ThreadLocal爲key找到對應的Entry,返回Entry的key爲當前的ThreadLocal對象,value爲對應的值ci

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

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

 

每一個線程都有一個ThreadLocalMap對象引用it

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

public void remove() {
     ThreadLocalMap m = getMap(Thread.currentThread());
     if (m != null)
         m.remove(this);
 }class

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

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

ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY];
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}

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

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

相關文章
相關標籤/搜索