说明
ThreadLocal 本意为线程本地变变量,或者说叫本地线程变量。通过他可以实现在同一个线程内实现数据共享。这里有个重点就是同一个线程内,如果不是同一个线程,自然就会失效。之前看过一本名叫《高并发程序设计》的书中将它比喻为人手一支笔,我理解的是,每个线程都可以自己给自己签名,而不需要排队去找别人签名,听起来比较有趣。
原理
先来看源码
package java.lang;
import java.lang.ref.*;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code 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).
*
*
* @author Josh Bloch and Doug Lea
* @since 1.2
*/
public class ThreadLocal<T> {
ThreadLocal类是在java.lang包下,JDK1.2版本之后就有了,我是在JDK1.8中查看的,可以明显的看到加了泛型,避免了早期版本中强制类型转化,提前约定好要储存的数据类型,在编译期就可以检查出问题。在注释中可以大概看到该类是提供一个线程局部变量,可以通过get、set操作线程自己独立初始化好的变量。ThreadLocal的实例通常作为私有的静态变量,通过它可以将线程的某个状态(比如User ID或者Transaction ID与当前线程关联起来。
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);
}
value就是需要储存在当前线程中的值的副本
大概流程是先获取当前线程对象,然后获取ThreadLocalMap对象,如果该map不为空,就将ThreadLocal实例作为key,要存放的值作为value放入map中,那么ThreadLocalMap是啥?接着看源码
/**
* 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;
}
getMap方法使用线程实例t中获取该实例变量,再看线程类
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
在Thread类中对该字段的注释可以看到这是一个和这个线程有关的线程本地值,这个map主要是通过ThreadLocal维护的。接着再看这个ThreadLocalMap类:
/**
* ThreadLocalMap is a customized hash map suitable only for
* maintaining thread local values. No operations are exported
* outside of the ThreadLocal class. The class is package private to
* allow declaration of fields in class Thread. To help deal with
* very large and long-lived usages, the hash table entries use
* WeakReferences for keys. However, since reference queues are not
* used, stale entries are guaranteed to be removed only when
* the table starts running out of space.
*/
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<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* Set the value associated with key.
*
* @param key the thread local object
* @param value the value to be set
*/
private void set(ThreadLocal<?> key, Object value) {
// We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
if (k == key) {
e.value = value;
return;
}
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
/**
* Remove the entry for key.
*/
private void remove(ThreadLocal<?> key) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
if (e.get() == key) {
e.clear();
expungeStaleEntry(i);
return;
}
}
}
}
这是一个Thread类中静态内部类,里面实现Entry键值对。提供了set、getEntry、remove等方法。
接着看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) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
现在就很容易理解get是如何取到之前set的数据的。
补充说明
-
使用ThreadLocal时,需要显示的关闭资源,也就是在调用remove方法,这样可以避免内存泄漏。当前不关闭也可以,在线程被回收的时候,也会随着被回收。从性能角度来说,最好是手动释放资源。
-
利用ThreadLocal的特性,可以保证多线程使用时线程安全,因为这个数据是单线程独有可见的,它储存在独立虚拟机栈帧中局部变量表中,与其他线程毫无瓜葛。
使用方式
- 在类中创建私有静态实例。比如获取线程唯一序列号线程唯一标识符’
UniqueThreadIdGenerator 。 - 封装在工具类中,来保证统一线程获取的信息一致
- 创建静态实例,通过 类名.实例名 访问。比如在登录后,可以在过滤器中解析请求对象所携带的非敏感的用户信息存放到ThreadLocal中,以便在后续的业务代码里随后获取登录用户信息。
仅仅个人理解,如果错误,多多指正