0
点赞
收藏
分享

微信扫一扫

ThreadLocal和InheritableThreadLocal源码学习

南柯Taylor 2022-04-14 阅读 55
java

InheritableThreadLocal 是 Threadlocal的扩展类,核心方法都在Threadlocal中,所以先来看这个类:

1. Threadlocal:

Threadlocal提供了线程内共享的变量。每个访问一个(通过它的get或set方法)的线程都有它自己的、独立初始化的变量空间,即Threadlocal为每个线程单独维护一份副本。 ThreadLocal可以用来在线程内部传递数据(例如,业务中的用户 ID 或事务 ID)。

既然与线程相关,可以看一下Thread的源码,里面有这样一个属性:

/* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

可以看到每个线程中都维护了一个ThreadlocalMap,map的key是Threadlocal对象,value是该线程中要传递的数据,并且key的哈希算法也是Threadlocal中定制的。

    //每次创建一个Threadlocal,就会分配一个对应的哈希码
    private final int threadLocalHashCode = nextHashCode();

    //注意是static的,所有对象共享,从0开始递增的哈希码
    private static AtomicInteger nextHashCode = new AtomicInteger();

    //每个哈希码之间的间隔,允许哈希值在map中均匀的分布,防止哈希冲突
    private static final int HASH_INCREMENT = 0x61c88647;

    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

因此想要在线程的map里添加数据,必须要在该线程中创建一个新的Threadlocal对象。只要线程处于活动状态并且ThreadLocal实例可访问,每个线程都持有对其线程局部变量副本的隐式引用(弱引用);在线程对象销毁后,该线程本地实例副本都将被GC回收(除非存在对这些副本的其他引用)。

//返回此线程局部变量的当前线程的“初始值”。该方法将在线程第一次使用get方法访问变量时调用,除非该线        //程之前调用了set方法,在这种情况下,不会为该线程调用initialValue方法。通常,每个线程最多调用一次
//此方法,但如果后续调用remove后跟get ,则可能会再次调用它。此实现仅返回null ;如果程序员希望线程
//局部变量具有除null以外的初始值,则必须将ThreadLocal子类化,并重写此方法。通常将使用匿名内部类。

    protected T initialValue() {
        return null;
    }

//这个方法使用了一个Supplier<? extends S>对象,其泛型继承了Threadlocal的泛型,也就是可以通过该对象的get方法为Threadlocal变量赋值
    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
        return new SuppliedThreadLocal<>(supplier);
    }
    
    //Threadlocal的静态内部类
    static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {

        private final Supplier<? extends T> supplier;

        SuppliedThreadLocal(Supplier<? extends T> supplier) {
            this.supplier = Objects.requireNonNull(supplier);
        }

        @Override
        protected T initialValue() {
            return supplier.get();
        }
    }

接下来要看它核心的get和set方法了:

    //这两个方法的逻辑是:先判断当前线程的ThreadlocalMap是否存在
    //如果存在直接获取值,如果不存在,创建新的map并设置初始化值
    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();
    }

    //initialValue()需要子类去实现
    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;
    }

    //与上一个方法极其类似
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

    //顺便把remove方法也带上吧
    public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

    //获取当前线程的ThreadlocalMap
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    

这里面用到的ThreadlocalMap,静态内部类,其操作方式跟HashMap类似,只不过哈希值计算的方法不一样,关键点请看注释:

    static class ThreadLocalMap {

        //这里的map结点继承了弱引用,同时可以看到构造方法里面,使用了super(k)
        //表明了这个节点的key是一个弱引用,这样保证了线程结束的时候,key不会出现
        //内存泄漏的问题,注意,k是Threadlocal对象,它本身有一个外部的引用指向他
        //但是这里仍然没有解决value的泄漏问题,所以当不需要Threadlocal对象的值时,
        //在每个线程中需要手动执行Threadlocal.remove()方法,否则会出现内存泄漏
        static class Entry extends WeakReference<ThreadLocal<?>> {
            
            Object value;

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

        //下面的属性和方法与HashMap类似
        private static final int INITIAL_CAPACITY = 16;

        
        private Entry[] table;

        
        private int size = 0;

      
        private int threshold;

       
        private void setThreshold(int len) {
            threshold = len * 2 / 3;
        }

     
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

 
        private static int prevIndex(int i, int len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }

        //懒加载方式,只有需要的时候才创建
        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);
        }

       
        private ThreadLocalMap(ThreadLocalMap parentMap) {
            Entry[] parentTable = parentMap.table;
            int len = parentTable.length;
            setThreshold(len);
            table = new Entry[len];

            for (int j = 0; j < len; j++) {
                Entry e = parentTable[j];
                if (e != null) {
                    @SuppressWarnings("unchecked")
                    ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
                    if (key != null) {
                        Object value = key.childValue(e.value);
                        Entry c = new Entry(key, value);
                        int h = key.threadLocalHashCode & (len - 1);
                        while (table[h] != null)
                            h = nextIndex(h, len);
                        table[h] = c;
                        size++;
                    }
                }
            }
        }

       
        private Entry getEntry(ThreadLocal<?> key) {
            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;

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

   
        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;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

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


        private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                       int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
            Entry e;


            int slotToExpunge = staleSlot;
            for (int i = prevIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = prevIndex(i, len))
                if (e.get() == null)
                    slotToExpunge = i;

            for (int i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;

                    tab[i] = tab[staleSlot];
                    tab[staleSlot] = e;

                    // Start expunge at preceding stale entry if it exists
                    if (slotToExpunge == staleSlot)
                        slotToExpunge = i;
                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
                    return;
                }

                if (k == null && slotToExpunge == staleSlot)
                    slotToExpunge = i;
            }

            tab[staleSlot].value = null;
            tab[staleSlot] = new Entry(key, value);

            if (slotToExpunge != staleSlot)
                cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
        }

        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;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

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

        private void rehash() {
            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis
            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();
                    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);
            }
        }
    }

2. InheritableThreadLocal:

有了Threadlocal的基础,这个就很好理解了,它允许被创建的子线程继承创建它的父线程的所有Threadlocal变量,也就是允许Threadlocal在父子线程(注意不是父子类)中传递。

    //这里直接传递了父线程的值,没有做任何处理
    protected T childValue(T parentValue) {
        return parentValue;
    }

    //可以看到每个线程中还专门维护了一个父子线程共享的ThreadlocalMap
    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }

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

相关推荐

0 条评论