ThreadLocal 翻译就是线程局部变量,就是这个变量只存在于当前的线程,只存在于当前的线程,那么完美解决了并发共享资源导致并发不安全的问题。
java.lang.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); // 1
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
// 1 从当前线程获取一个ThreadLocalMap,ThreadLocalMap.java是Thread中的一个静态内部类,让我们看一下ThreadLocalMap.Entry类。
java.lang.ThreadLocal.ThreadLocalMap.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); // 1
value = v;
}
}
注释中说道当entry.get() == null 代表key不再被引用,这个entry可以从table中释放了,也可以看到Entry.java继承了WeakReference.java(弱引用)
弱引用概念
弱引用也是用来描述那些非必须对象,但是它的强度比软引用更弱一些,被弱引用关联的对象只
能生存到下一次垃圾收集发生为止。当垃圾收集器开始工作,无论当前内存是否足够,都会回收掉只被弱引用关联的对象。在JDK 1.2版之后提供了WeakReference类来实现弱引用。
// 1 代码 super(k); 可以看出ThreadLocal 作为WeakReference的referent。那么在下一次垃圾回收时ThreadLocal会被回收掉。
让我们理一下引用关系 Thread->ThreadLocalMap-> Entry[]->Entry-> ThreadLocal 和 Value。ThreadLocal回收后,看一下getEntry方法,发现getEntry方法将无法获取到Entry,也就无法获取到value。此时这个value无法被获取的,也就是发生了内存泄漏。
java.lang.ThreadLocal.ThreadLocalMap#getEntry
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);
}
如果当前ThreadLocal匹配不到key,那么将调用getEntryAfterMiss方法。
java.lang.ThreadLocal.ThreadLocalMap#getEntryAfterMiss
/**
* 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) // 1 key为null,释放Entry。
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
注释:for use when key is not found in its direct hash slot。
// 1 key为null,释放Entry。
java.lang.ThreadLocal.ThreadLocalMap#expungeStaleEntry
/**
* Expunge a stale entry by rehashing any possibly colliding entries
* lying between staleSlot and the next null slot. This also expunges
* any other stale entries encountered before the trailing null. See
* Knuth, Section 6.4
*
* @param staleSlot index of slot known to have null key
* @return the index of the next null slot after staleSlot
* (all between staleSlot and this slot will have been checked
* for expunging).
*/
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// Rehash until we encounter null
Entry e;
int i;
for (i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null;
tab[i] = null;
size--;
} else {
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
这里不禁让人思考为什么这里要使用WeakReference?是有助于避免内存泄漏吗?
使用WeakReference,可以在ThreadLocal是弱引用时回收。value在java.lang.ThreadLocal.ThreadLocalMap#getEntryAfterMiss ,java.lang.ThreadLocal.ThreadLocalMap#expungeStaleEntry 方法中进行回收掉。
每次调用完成后都调用ThreadLocal.remove() 方法完全可以避免这个内存泄漏问题。
真正的内存泄漏的情况
当threadLocal对象设为null时,value再也无法获取到,发生了内存泄漏,然后使用线程池,这个线程结束,线程放回线程池中不销毁,这个线程一直不被使用,或者分配使用了又不再调用ThreadLocal.get,ThreadLocal.set方法,那么这时就会发生真正的内存泄露。
内存泄漏的Demo
环境:java1.8
虚拟机启动参数:-Xms64M -Xmx64M
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalMemoryLeak {
private static ExecutorService executorService = Executors.newFixedThreadPool(100);
public static void main(String[] args) throws InterruptedException, NoSuchFieldException, IllegalAccessException {
for (int i = 0; i <80 ; i++) {
// 等待垃圾回收执行
Thread.sleep(100);
ThreadLocal<ByteObject> threadLocal = new ThreadLocal<ByteObject>(){
@Override
protected ByteObject initialValue() {
return new ByteObject();
}
};
executorService.execute(()->{
threadLocal.get();
// 不remove将导致内存溢出
//threadLocal.remove();
});
}
Thread.sleep(3000);
executorService.shutdown();
}
public static class ByteObject{
// 5MB
private byte [] bytes = new byte[5*1024*1024];
@Override
protected void finalize() throws Throwable {
System.out.println(" finalize");
}
}
}
注释掉remove代码,将导致内存溢出。threadLocal初始化代码 放在for循环里,for循环后不再被引用,在垃圾回收的时候将释放内存。因为线程词核心线程数100 大于需要的线程数80,不会触发在同一个线程调用get方法,所以导致ByteObject不会被释放而内存溢出。
如果将核心线程池改为1,此时无需remove,也不会存在内存溢出的情况,因为重复调用同一个线程的get方法,所以也会触发回收ByteObject。
在for循环开始初我sleep 100 毫秒,让垃圾回收有时间进行,否则,即使不注释掉remove也会导致内存溢出。
参考资料
ThreadLocal (Java Platform SE 8 )
关于Java中的WeakReference
ThreadLocal源码解读
网友评论