ThreadPoolExecutor 与 ThreadLocal 配合使用中出现数据不一致

ThreadPoolExecutor 与 ThreadLocal 配合使用中出现数据不一致问题

前段时间写过一段测试代码,发现使用了ThreadLocal出现了数据不一致的问题,之前也一直用过,没有出现过.所以感到很疑惑.于是针对这个case研究了下源码

  • 单元测试代码
/**
 * 

* 测试ThreadLocal结合ThreadPoolExecutor是否存在数据不安全情况 *

* * @author sunla * @version 1.0 */ public class ThreadLocalTest { private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(2, 2, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque(20), new ThreadFactoryBuilder().setNameFormat("name-%s").build(), new ThreadPoolExecutor.AbortPolicy()); private static final ThreadLocal LOCAL = new ThreadLocal(); @Test public void startTest() throws Exception { LOCAL.set("main start"); EXECUTOR.execute(()->{ System.out.println( String.format("value is %s", LOCAL.get())); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println( String.format("value is %s", LOCAL.get())); } }
  • 输出结果
NULL
main start

很奇怪.ThreadLocal 就是为了保持回话中变量共享 为什么不一致呢
我们平时使用ThreadLocal的场景 可以理解为会话中的数据共享,那怎么在这里出现了与期望不一致的结果呢?其实这跟ThreadLocal的内部实现有关系.

ThreadLocal 内部实现

/**
     * 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是内部实现的map
         *  特点是key是ThreadLocal的引用
         *  至于为什么这样设计?我们往下看   
         */
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    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都有独立的threadlocalmap */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
  • ThreadLocalMap实现
static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal k, Object v) {
                super(k);
                value = v;
            }
        }
        //TO DO
  }

看了threadLocal的实现 我们知道了,原来thread local 实例有个map 存储的key就是线程的引用,value就是需要共享的变量.
那我们上面的代码 难道获取的不是同一个线程?
看过ThreadPoolExecutor实现的就知道 真的不是一个
ThreadPoolExecutor 实现

/**
* 添加工作线程
*/
private boolean addWorker(Runnable firstTask, boolean core) {
        //TO DO
        w = new Worker(firstTask);
        final Thread t = w.thread;
        //TO DO
    }
/** 工作类 实现runnable接口 */
private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
        Worker(Runnable firstTask) {
            setState(-1);
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }
        /** 重写run方法 最终执行的就是runWorker */
        public void run() {
            runWorker(this);
        }
    }

这下真相大白了,原因在线程池中会开辟新的线程执行task.如果在主线程中(main) 放入到ThreadLocal的value在task中获取到的就不再是main线程的ref了.而且线程池自己开辟的. 所以导致数据不一致.

这里提个问题 threadlocal有个remove方法,
如果我们不显示调用 会怎么样?

你可能感兴趣的:(ThreadPoolExecutor 与 ThreadLocal 配合使用中出现数据不一致)