ThreadLocal 源码分析

ThreadLocal可以实现以线程为作用域来存储数据。在A线程中存储的ThreadLocal数据只有A线程才能看到,其它线程看不到。下面来看一个具体应用的例子:

public class ThreadLocalTest {
    public static void main(String[] args) {
        ThreadLocal<Boolean> threadLocal = new ThreadLocal<>();
        threadLocal.set(true);
        System.out.println("Thread#main " + threadLocal.get() + " hashCode of threadLocal = " + threadLocal.hashCode());

        new Thread("Thread#1") {
            @Override
            public void run() {
                Map map = new HashMap();
                threadLocal.set(false);
                System.out.println("Thread#1" + threadLocal.get() + " hashCode of threadLocal = " + threadLocal.hashCode());
            }
        }.start();

        new Thread("Thread#2") {
            @Override
            public void run() {
                System.out.println("Thread#2" + threadLocal.get() + " hashCode of threadLocal = " + threadLocal.hashCode());
            }
        }.start();
    }
}

输出如下:

Thread#main true hashCode = 1639705018
Thread#1 false hashCode = 1639705018
Thread#2 null hashCode = 1639705018

从上面输出我们可以看到,一个ThreadLocal对象在不同的线程中调用set() 方法存储数据,然后用 get() 方法获取到的数据值是不同的。那么这是怎么做到的呢?我们首先来看一下 set()get() 方法的源码:

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

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

set() 方法中,通过 getMap 方法获取了一个 ThreadLocalMap 类型的对象,我们可以猜到这是一个map,然后以当前ThreadLocal对象最为key,传进来的值作为value,把这个键值对存入map。来看一下 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;
    }

这里我们可以看到,这个Map 是 Thread 中的一个成员变量,是由Thread 来持有的,这也就可以解释刚才为什么通过同一个ThreadLocal对象在不同的Thread中做set和get操作会得到不同的值,因为每个Thread中的ThreadLocalMap存的值是不一样的。
在set方法中,如果 getMap的返回值不为null,则把键值对存入map,否则,调用createMap为当前Thread初始化一个ThreadLocalMap:

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

同理,get 的时候,也要先拿到当前Thread 的 ThreadLocalMap 对象,key 还是当前的ThreadLocal对象,从map中取的value。如果map.getEntry 返回 null,说明map中没有这个键,那么返回 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);
        }
        if (this instanceof TerminatingThreadLocal) {
            TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
        }
        return value;
    }

setInitialValue() 的返回值 value 实际上是 initialValue() 的返回值,代码就不贴了,默认返回null

Reference:
[1] 《Android开发艺术探索》-- 任玉刚
[2] JDK1.8 java.lang.ThreadLocal 源码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值