ThreadLocal原理

ThreadLocal是什么?看Java源码中的描述:

 

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

 

ThreadLocal通过ThreadLocalMap与当前线程绑定到一起(如下图)。

 

 

每一个Thread对象,专门用一个ThreadLocalMap来存储自己专用的变量。ThreadLocalMap其实就跟我们平时常用的HashMap类似,能够存储Key-Value形式的数据。在这里,ThreadLocalMap的Key是一个ThreadLocal对象。

 

ThreadLocal在每次get或set操作时,都会先通过Thread.currentThread()方法来获取当前线程,再从当前线程中获取ThreadLocalMap。表面上看,ThreadLocal像是一个变量体(或者说是存储变量的容器),而实际上,它是通过Map来存储的。

 

一个ThreadLocal对象可以是多线程共享,但一个ThreadLocalMap对象却是某个线程独享的,即每一个Thread对象,都会创建一个自己专用的ThreadLocalMap,与其他Thread对象创建的ThreadLocalMap不存在相等关系。

 

当多个Thread对象共同访问同一个ThreadLocal对象时,threadLocal只是作为ThreadLocalMap的Key存在,而不作为变量的存储介质。threadLocal的set()方法和get()方法所涉及的value是存储为ThreadLocalMap的value。而ThreadLocalMap是每一个Thread各自专用的,互不相等的。这就是为什么同ThreadLocal被多线程同时访问,ThreadLocal的值却互不干扰的原理。

 

贴一下ThreadLocal的get()、set()、remove()方法的代码,从代码中看,更容易理解!

 

    /**
     * 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)
                return (T)e.value;
        }
        return setInitialValue();
    }

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

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值