深入理解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类提供以下四个主要的方法:
-
public T get()
-
public void set(T value)
-
public void remove()
-
protected T initialValue()
先来看ThreadLocal的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)
-
return (T)e.value;
-
}
-
return setInitialValue();
-
}
这里有个ThreadLocalMap,关于这个,看到有的博客上有争议,说是属于Thread的,还是ThreadLocal的。来看源码,首先,ThreadLocalMap是ThreadLocal的内部类,然而,这并不代表是ThreadLocal中有一个map,看Thread类源码中有这么一句:
ThreadLocal.ThreadLocalMap threadLocals = null;
因此应该是每个Thread维护了一个ThreadLocalMap,也就是说,ThreadLocalMap的实例是在Thread中的,而这个map的key正是ThreadLocal。再回过来看get方法,第一步是得到当前线程,再是得到当前线程的ThreadLocalMap,其中getMap(t)代码如下,
-
/**
-
* 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不为空,得到Entry,其中Entry就是以ThreadLocal为key的map的弱引用,
-
/**
-
* 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<ThreadLocal> {
-
/** The value associated with this ThreadLocal. */
-
Object value;
-
Entry(ThreadLocal k, Object v) {
-
super(k);
-
value = v;
-
}
-
}
如果entry不为空,则返回其对应的value。如果map为空,则执行setInitialValue()方法进行初始化。
再来看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);
-
}
前面两步是一样的,如果得到的map不为空,就set值,因为set方法是ThreadLocal对象调用的,所以这里的this其实就是调用该方法的ThreadLocal对象,也再次说明了ThreadLocalMap的key就是ThreadLocal。如果map为空,则重新创建一个。其中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
-
* @param map the map to store.
-
*/
-
void createMap(Thread t, T firstValue) {
-
t.threadLocals = new ThreadLocalMap(this, firstValue);
-
}
其次是remove()方法。
-
/**
-
* 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);
-
}
该方法移除以ThreadLocal为key的value。
最后是initialValue()方法。
-
/**
-
* Returns the current thread's "initial value" for this
-
* thread-local variable. This method will be invoked the first
-
* time a thread accesses the variable with the {@link #get}
-
* method, unless the thread previously invoked the {@link #set}
-
* method, in which case the <tt>initialValue</tt> method will not
-
* be invoked for the thread. Normally, this method is invoked at
-
* most once per thread, but it may be invoked again in case of
-
* subsequent invocations of {@link #remove} followed by {@link #get}.
-
*
-
* <p>This implementation simply returns <tt>null</tt>; if the
-
* programmer desires thread-local variables to have an initial
-
* value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be
-
* subclassed, and this method overridden. Typically, an
-
* anonymous inner class will be used.
-
*
-
* @return the initial value for this thread-local
-
*/
-
protected T initialValue() {
-
return null;
-
}
这个方法返回该线程局部变量的初始值,该方法是一个protected的方法,显然是为了让子类覆盖而设计的。这个方法是一个延迟调用方法,在线程第一次调用get()或set()时才执行,并且仅执行一次。ThreadLocal的缺省实现直接返回一个null。
那么ThreadLocal有什么使用场景。
在Java多线程编程中,为保证多个线程对共享变量的安全访问,通常会使用synchronized来保证同一时刻只有一个线程对共享变量进行操作,这种情况下可以将类变量放到ThreadLocal类型的对象中,使变量在每个线程中都有独立拷贝,不会出现一个线程读取变量时被另一个线程修改的现象。
ThreadLocal是解决线程安全问题一个很好的思路,它通过为每个线程提供一个独立的变量副本解决了变量并发访问的冲突问题。在很多情况下,ThreadLocal比直接使用synchronized同步机制解决线程安全问题更简单,更方便,且结果程序拥有更高的并发性。