使用场景
ThreadLocal用来提供线程局部变量。每个线程都会有一份独立的副本,副本之间不存在竞争关系,是线程专属的内存空间。
例如:
public class ThreadLocalTest {
private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
threadLocal.set(0);
for (int i = 0; i < 100; i++) {
threadLocal.set(threadLocal.get() + 1);
Thread.yield();
}
System.out.println(threadLocal.get());
});
Thread thread2 = new Thread(() -> {
threadLocal.set(0);
for (int i = 0; i < 100; i++) {
threadLocal.set(threadLocal.get() + 1);
Thread.yield();
}
System.out.println(threadLocal.get());
});
thread1.start();
thread2.start();
}
}
运行的结果
100
100
循环时增加yield()尽可能让thread1和thread2发生竞争。无论运行多少次,结果都是2个100不会变。由此可见,虽然两个线程实例共用同一个ThreadLocal实例,使用的Integer也不是线程安全类,但是没有出现资源抢占引起的数据错误。
源码解读
通过看源码来了解如何做到这一切的。
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();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
ThreadLocal的get()和set()方法,首先会获取当前线程实例,然后读取当前线程的ThreadLocalMap实例,这是从Thread的私有属性threadLocals获取到的,不同实例不共享的,所以对各自的ThreadLocalMap操作也就不存在并发问题。
ThreadLocalMap是ThreadLocal的内部静态类,是由Entry数组实现的Map,但与常用的HashMap等Map不同的是,发生Hash冲突上的处理、和垃圾数据的清理。这一块可以后面再细说
ThreadLocalMap的key是ThreadLocal实例的引用,value是ThreadLocal类get()和set()方法操作的值。
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;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
...
}
如下图,梳理了Thread、ThreadLocal、ThreadLocalMap、Entry这几个主要的类之间的引用关系
每个线程持有的这份独立副本,只有在线程销毁时才会被GC清理,除非这份副本还被其他强引用关联。
上图中的虚线代表的是弱引用WeakReference。由图看出,在某一个Thread实例被销毁时,对应的ThreadLocalMap实例的key还在被ThreadLocal实例引用,是GCRoot可达的,如果此处是强引用,那就不会被GC回收,线程被多次创建销毁后,会出现OOM问题。
还有一个点需要注意,为了降低线程频繁创建销毁带来的性能开销,通常会使用线程池,这就意味着,线程在使用完后并不一定会被销毁,可能会被反复使用,那么线程的这份副本可能有脏读的现象,如果value是个集合类,可能还会出现value不断被添加元素导致内存占用不断变大直至OOM。所以在线程池中使用ThreadLocal在线程使用完后要及时去手动remove()清理。