ThreadLocal
一个例子
public class ThreadLocalTest {
private static ThreadLocal<Long> threadLocal = new ThreadLocal<Long>() {
@Override
protected Long initialValue() {
return 1L;
}
};
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
new Thread(()->{
Long local = threadLocal.get();
local++;
threadLocal.set(local);
System.out.println(Thread.currentThread().getId() + " get: " + threadLocal.get());
}).start();
}
}
}
output:
11 get: 2
14 get: 2
12 get: 2
13 get: 2
按常规来说,变量threadLocal定义成了全局变量,值应该是共享的,任何一个线程更改之后,其他线程应该也会更改,但是运行发现结果都一样,多线程互不影响.
ThreadLocal
是如何实现多线程隔离的.
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的set方法时,户先调用当前线程的getMap(),而getMap()返回了当前线程Thread的
threadLocals成员变量,类型为ThreadLocal.ThreadLocalMap,也就是说每个线程维护了自己的一个ThreadLocalMap
第一次threadLocals==null,直接createMap(t, value)
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
createMap(t, value)方法创建了以当前线程为key,set的值为value的Entity,并根据ThreadLocal的nextHash求得Entity在table数组中的下标位置,放入ThreadLocalMap中的table数组
当调用ThreadLocal.get()时
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();
}
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
还是先根据线程取获取当前线程的ThreadLocalMap,然后根据ThreadLocal的nextHash求出Entity在table数组中的下标,返回Entity的value值
显而易见,ThreadLocal对于多线程的的安全隔离是让每个线程维护自己的ThreadLocalMap,每个线程互不影响
大概结构是这样的
每个线程set的时候实际上set的是自己的ThreadLocalMap中指定ThreadLocal的entity的value,并不会影响其他线程中的值