- 例子
先看一个简单使用的列子。
static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
for (int i=0;i<10;i++) {
new Thread(){
@Override
public void run() {
if (threadLocal.get() == null) {
System.out.println("threadlocal is null");
threadLocal.set(Thread.currentThread().getName());
}
System.out.println("thradlocal has set data:" + threadLocal.get());
}
}.start();
}
}
ThreadLocal可以理解为线程本地变量。也就是单个线程独享的变量不受其他线程影响,主要用于存储线程私有变量,避免线程安全问题,做到线程间的隔离。
- 源码解读
从我们最开始使用它的地方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);
}
在这个方法里,它拿到当前对象,然后用当前对象作为参数取getMap()获取到一个ThreadLocalMap对象,如果不为空就给他set值,为空就createMap()。ThreadLocalMap到底是什么,接着往下看getMap()方法。
/**
* 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;
}
再继续看Thread类
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
看到这里可以发现,每个Thread对象都持有一个ThreadLocalMap类型的threadLocals变量,默认为null。
然后看看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
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
就只是new了一个ThreadLocalMap对象,传入的参数是当前线程ThreadLocal对象,和我们刚刚调set()传入的值,往下看ThreadLocalMap构造方法
/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
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);
}
/**
* 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;
table是给Entry类型的数组,初始长度16,传进来的threadlocal对象和object值,new了一个Entry对象保存,然后通过threadlocal的hash值放在table的一个指定位置。我们看看entry这个对象。
/**
* 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;
}
}
这是个弱引用对象,为啥是弱引用,看完源码再来分析。
当这个ThreadLocalMap已经创建l,就会调用set方法给他set值。
/**
* 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();
}
这里的难点在这个for循环。通过hash值找到key的位置,然后从这个位置开始往后遍历数组(到数组最后,从0开始,nextIndex()方法),知道出现为空退出。为什么要这样呢,它这个map不想hashmap是一个数组+链表的结构,它只有数组,如果set的时候,算出来的hash值,这个地方已经有元素了(hash冲突了),它就往后放。所以这个循环呢,就是找出可以放entry的位置。
循环的过程中有两个特色情况:一个是我这个key已经存在table里面了,替换即可。另一个是出现了table[i]得到的entry的引用不为空,但是它里面的threadlocal为空了,也就是出现弱引用,被GC回收了的情况,这个时候调用replaceStaleEntry()替换掉这个entry。
这时候在想会不会出现数组table放满的情况,导致循环出不来呢?不会。看这个方法的最后两行,cleanSomeSlots()方法会移除所有那些因为弱引用被GC的对象。当size达到threshold(len的2/3)的时候会rehash重新计算hash,满足条件还会resize重新设置table大小。这里的size和len区分一下,len是table的大小,size是table中实际对象的多少。
然后从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();
}
获取当前对象的ThreadLocalMap,getEntry()获取对应this的entry,去除,如果为空,设置初始值setInitialValue()。
protected T initialValue() {
return null;
}
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
*
* @return the initial value
*/
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
设置初始值就是创建好ThreadLocalMap,并set个null。看看getEntry()方法。
/**
* Get the entry associated with key. This method
* itself handles only the fast path: a direct hit of existing
* key. It otherwise relays to getEntryAfterMiss. This is
* designed to maximize performance for direct hits, in part
* by making this method readily inlinable.
*
* @param key the thread local object
* @return the entry associated with key, or null if no such
*/
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);
}
/**
* Version of getEntry method for use when key is not found in
* its direct hash slot.
*
* @param key the thread local object
* @param i the table index for key's hash code
* @param e the entry at table[i]
* @return the entry associated with key, or null if no such
*/
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
while (e != null) {
ThreadLocal<?> k = e.get();
if (k == key)
return e;
if (k == null)
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
算出hash值,找到对应位置的entry,看key是否相等,不相等或者entry为空,那就getEntryAfterMiss()循环找,这个方法也会调用expungeStaleEntry清理掉被回收了的entry。
再看看remove方法
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
...
/**
* 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;
}
}
}
与get方法很类似,不做说明了。
最后研究上述留下的问题,为啥要用弱引用。现在的引用关系是这样的,Thread对象持有一个ThreadLocalMap的引用,ThreadLocalMap对象持有多个ThreadLocal的引用,然后,我们定义和使用threadlocal也会有一个ThreadLocal的引用,也就是有两个地方持有了ThreadLocal的引用。咋一看,没有什么问题,在线程运行过程中创建了ThreadLocal对象,程序跑完了,ThreadLocal对象销毁的时候线程也销毁了。但是呢,有种情况——线程池,在这个特殊情况下,可能存在程序跑完了,ThreadLocal要销毁了,但是线程它还活着,重复利用了,如果Thread强引用ThreadLocal,在GC要回收的时候,回收不了,就出现了内存泄漏。使用弱引用就是避免了内存泄漏。
值的我们注意的还有一个问题,使用弱引用的只有ThreadLocal,value并没有弱引用。虽然,在set()和get()的时候,都会清掉key 为null的entry,那如果一直没有进行set()或get(),那这个value就一直没法被回收,这里也是有内存泄漏风险的。使用ThreadLocal的时候最好,在用完后remove,避免内存泄漏