ThreadLocal详解

Posted 叶长风

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ThreadLocal详解相关的知识,希望对你有一定的参考价值。

ThreadLocal详解


ThreadLocal平常用的还是挺多的,但是对于内部实现一直没有仔细了解过,这几天在写一个工程的时候,用到了ThreadLocal保存上下文,突然想到了ThreadLocal一些实现细节上的问题,看了下,同时以此记录一下,原本想到直接就写ThreadLocal,但是看了ThreadLocal源码发现有很多地方需要单独说下,比如ThreadLocal的寻址方式,ThreadLocal内存泄露等等,而关于寻址方式,ThreadLocal的寻址方式为开放寻址法,和HashMap的数组加链表方式并不相同,而对于解决hash碰撞冲突,有好多种解决方法,因此对于寻址方式,单独写一篇文章用以记载,现在就把剩下的详细讲讲,此处并不限于只讲源码,还有用途,设计等等。

源码详解


首先写个最简单的用法,如下:

private static ThreadLocal<Context> ctxMap;

    static 
        ctxMap = new ThreadLocal<>();
    

    public static void set(Context ctx) 
        ctxMap.set(ctx);
    

    public static Context get() 
        return ctxMap.get();
    

写了一段样例,最简单的实例化ThreadLocal对象,同时实现get、set方法,现在就从实例化ThreadLocal开始,进ThreadLocal看看。

/**
     * Creates a thread local variable.
     * @see #withInitial(java.util.function.Supplier)
     */
    public ThreadLocal() 
    

是一个空的构造方法,这里一般都是适用于在请求初始时就需要对当前上下文进行set操作,要不然后面get操作很有可能就会出现空指针的情况,所以一般使用方法为在初始化时进行init操作,如下:

ctxMap = new ThreadLocal<Object>() 
            @Override
            protected Object initialValue() 
                return new Object();
            
        

这样可以保证即使是没有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();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    

set中的操作比较简单,获取当前线程,根据当前线程获取ThreadLocalMap对象,然后当前ThreadLocalMap对象如果存在则保存value,如果不存在则创建ThreadLocalMap对象,简单的看下getMap方法。

/**
     * 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;
    

就是返回当前线程的threadLocals对象,这里不做深究,后面还会再讲,接着继续看之前的代码,看set中的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) 
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    

和预料的差不多,就是给当前threadLocals对象进行实例化操作,这里我们不妨看下ThreadLocalMap的结构,直接进入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 = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        

这里操作没有太多可以讲述的,就是实例化, table数组大小为16,同时设置阈值。

我们回到map的set操作,进入set方法源码。

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

根据key算出i坐标值后,然后获取当前索引下是否有值,如果当前槽点有值,并且当前槽点下key和当前传入的key相同,则直接进行value替换,如果当前槽点key为null,但是存在值,则进行槽点值替换操作,这个就是替换内存泄露的数据,这个需要讲述的比较多,分为两篇,这个在后面单独讲述,这里还是讲get、set、remove等操作的源码。

上述三种情况,一种是当该槽点的key就是当前要保存的key时,直接进行value替换。另外一种是如果value不为空,但是key为空,则进行替换,这个在下一篇中单独讲,第三种情况就是该节点不为空,此时就使用了线性探测法向下寻找下一个可用节点,此时如果寻找到一个可用节点,则进行新Entry插入操作,此时并且检测当前占满槽点已经超过阈值,则进行扩容操作,可以进入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()方法放到下一节中再进行讲述,直说resize方法。这里当使用节点数大于当前总数的3/4时,便进行扩容操作,这里3/4容量就是一个经验值,在前人经过反复试验以后,发现使用容量在3/4时扩容碰撞次数较少。

这里进入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 (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;
        

resize方法倒是挺简单,就是新建table,容量为当前的2倍,然后进行kv的替换。

现在回头看看get方法和remove方法,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) 
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            
        
        return setInitialValue();
    

get操作比较简单,就是从当前map中取出当前key对应的value即可,估计revome操作也是类似,一起来看下。

/**
     * 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
     * @code initialValue method in the current thread.
     *
     * @since 1.5
     */
     public void remove() 
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     

操作还是比较简单,就是获取map,然后remove当前对象。

ThreadLocal这些方法还是比较简单,但是这里得单独讲讲ThreadLocal处理脏key的办法,这个放在下一节来讲。

以上是关于ThreadLocal详解的主要内容,如果未能解决你的问题,请参考以下文章

ThreadLocal用法详解和原理

ThreadLocal详解

ThreadLocal详解(附面试题)

ThreadLocal详解

ThreadLocal 详解

ThreadLocal类详解