深入理解ThreadLocal

深入理解ThreadLocal

 https://blog.csdn.net/u014026363/article/details/51018829

        在之前的项目中涉及到了ThreadLocal的使用,因此看了jdk源码。在此分析部分源码,阐述一些自己的理解。

        首先来看ThreadLocal是什么。JDK 1.2的版本中就提供java.lang.ThreadLocal,ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序,ThreadLocal并不是一个Thread,而是Thread的局部变量。既然是局部变量,自然是每个Thread所私有的,Thread之间并不能共享。

        ThreadLocal类提供以下四个主要的方法:

 

 
  1. public T get()

  2. public void set(T value)

  3. public void remove()

  4. protected T initialValue()


        先来看ThreadLocal的get()方法。

 

 

 
  1. /**

  2. * Returns the value in the current thread's copy of this

  3. * thread-local variable. If the variable has no value for the

  4. * current thread, it is first initialized to the value returned

  5. * by an invocation of the {@link #initialValue} method.

  6. *

  7. * @return the current thread's value of this thread-local

  8. */

  9. public T get() {

  10. Thread t = Thread.currentThread();

  11. ThreadLocalMap map = getMap(t);

  12. if (map != null) {

  13. ThreadLocalMap.Entry e = map.getEntry(this);

  14. if (e != null)

  15. return (T)e.value;

  16. }

  17. return setInitialValue();

  18. }


        这里有个ThreadLocalMap,关于这个,看到有的博客上有争议,说是属于Thread的,还是ThreadLocal的。来看源码,首先,ThreadLocalMap是ThreadLocal的内部类,然而,这并不代表是ThreadLocal中有一个map,看Thread类源码中有这么一句:

 

 ThreadLocal.ThreadLocalMap threadLocals = null;

因此应该是每个Thread维护了一个ThreadLocalMap,也就是说,ThreadLocalMap的实例是在Thread中的,而这个map的key正是ThreadLocal。再回过来看get方法,第一步是得到当前线程,再是得到当前线程的ThreadLocalMap,其中getMap(t)代码如下,

 

 

 
  1. /**

  2. * Get the map associated with a ThreadLocal. Overridden in

  3. * InheritableThreadLocal.

  4. *

  5. * @param t the current thread

  6. * @return the map

  7. */

  8. ThreadLocalMap getMap(Thread t) {

  9. return t.threadLocals;

  10. }

然后如果map不为空,得到Entry,其中Entry就是以ThreadLocal为key的map的弱引用,

 

 

 
  1. /**

  2. * The entries in this hash map extend WeakReference, using

  3. * its main ref field as the key (which is always a

  4. * ThreadLocal object). Note that null keys (i.e. entry.get()

  5. * == null) mean that the key is no longer referenced, so the

  6. * entry can be expunged from table. Such entries are referred to

  7. * as "stale entries" in the code that follows.

  8. */

  9. static class Entry extends WeakReference<ThreadLocal> {

  10. /** The value associated with this ThreadLocal. */

  11. Object value;

  12.  
  13. Entry(ThreadLocal k, Object v) {

  14. super(k);

  15. value = v;

  16. }

  17. }

如果entry不为空,则返回其对应的value。如果map为空,则执行setInitialValue()方法进行初始化。

 

        再来看set()方法。

 

 
  1. /**

  2. * Sets the current thread's copy of this thread-local variable

  3. * to the specified value. Most subclasses will have no need to

  4. * override this method, relying solely on the {@link #initialValue}

  5. * method to set the values of thread-locals.

  6. *

  7. * @param value the value to be stored in the current thread's copy of

  8. * this thread-local.

  9. */

  10. public void set(T value) {

  11. Thread t = Thread.currentThread();

  12. ThreadLocalMap map = getMap(t);

  13. if (map != null)

  14. map.set(this, value);

  15. else

  16. createMap(t, value);

  17. }

        前面两步是一样的,如果得到的map不为空,就set值,因为set方法是ThreadLocal对象调用的,所以这里的this其实就是调用该方法的ThreadLocal对象,也再次说明了ThreadLocalMap的key就是ThreadLocal。如果map为空,则重新创建一个。其中createMap()方法如下。

 

 
  1. /**

  2. * Create the map associated with a ThreadLocal. Overridden in

  3. * InheritableThreadLocal.

  4. *

  5. * @param t the current thread

  6. * @param firstValue value for the initial entry of the map

  7. * @param map the map to store.

  8. */

  9. void createMap(Thread t, T firstValue) {

  10. t.threadLocals = new ThreadLocalMap(this, firstValue);

  11. }

 

        其次是remove()方法。

 

 
  1. /**

  2. * Removes the current thread's value for this thread-local

  3. * variable. If this thread-local variable is subsequently

  4. * {@linkplain #get read} by the current thread, its value will be

  5. * reinitialized by invoking its {@link #initialValue} method,

  6. * unless its value is {@linkplain #set set} by the current thread

  7. * in the interim. This may result in multiple invocations of the

  8. * <tt>initialValue</tt> method in the current thread.

  9. *

  10. * @since 1.5

  11. */

  12. public void remove() {

  13. ThreadLocalMap m = getMap(Thread.currentThread());

  14. if (m != null)

  15. m.remove(this);

  16. }

        该方法移除以ThreadLocal为key的value。
        最后是initialValue()方法。

 
  1. /**

  2. * Returns the current thread's "initial value" for this

  3. * thread-local variable. This method will be invoked the first

  4. * time a thread accesses the variable with the {@link #get}

  5. * method, unless the thread previously invoked the {@link #set}

  6. * method, in which case the <tt>initialValue</tt> method will not

  7. * be invoked for the thread. Normally, this method is invoked at

  8. * most once per thread, but it may be invoked again in case of

  9. * subsequent invocations of {@link #remove} followed by {@link #get}.

  10. *

  11. * <p>This implementation simply returns <tt>null</tt>; if the

  12. * programmer desires thread-local variables to have an initial

  13. * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be

  14. * subclassed, and this method overridden. Typically, an

  15. * anonymous inner class will be used.

  16. *

  17. * @return the initial value for this thread-local

  18. */

  19. protected T initialValue() {

  20. return null;

  21. }

        这个方法返回该线程局部变量的初始值,该方法是一个protected的方法,显然是为了让子类覆盖而设计的。这个方法是一个延迟调用方法,在线程第一次调用get()或set()时才执行,并且仅执行一次。ThreadLocal的缺省实现直接返回一个null。

 

        那么ThreadLocal有什么使用场景。

        在Java多线程编程中,为保证多个线程对共享变量的安全访问,通常会使用synchronized来保证同一时刻只有一个线程对共享变量进行操作,这种情况下可以将类变量放到ThreadLocal类型的对象中,使变量在每个线程中都有独立拷贝,不会出现一个线程读取变量时被另一个线程修改的现象。

        ThreadLocal是解决线程安全问题一个很好的思路,它通过为每个线程提供一个独立的变量副本解决了变量并发访问的冲突问题。在很多情况下,ThreadLocal比直接使用synchronized同步机制解决线程安全问题更简单,更方便,且结果程序拥有更高的并发性。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值