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,threadLocals 是Thread中的一个变量,ThreadLocalMap是Thread中的一个静态内部类。
Thread 类中的变量 threadLocals
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
ThreadLocalMap
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;
ThreadLocalMap的Entry 类 注释中说道当entry.get() == null 代表key不再被引用,这个entry可以从table中释放了,也可以看到Entry.java继承了WeakReference.java(弱引用)
看到Entry[]table 变量 和Entry类,可以理出来 引用关系为 Thread->ThreadLocalMap-> Entry[]->Entry-> ThreadLocal 和 Value。
引用概念
强引用
强引用是使用最普遍的引用。如果一个对象具有强引用,那垃圾回收器绝不会回收它。
软引用
如果一个对象只具有软引用,则内存空间充足时,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。
弱引用
弱引用也是用来描述那些非必须对象,但是它的强度比软引用更弱一些,被弱引用关联的对象只能生存到下一次垃圾收集发生为止。当垃圾收集器开始工作,无论当前内存是否足够,都会回收掉只被弱引用关联的对象。在JDK 1.2版之后提供了WeakReference类来实现弱引用。
public static void main(String[] args) {
WeakReferenceObject weakReferenceObject = new WeakReferenceObject();
WeakReference<WeakReferenceObject> weakReference = new WeakReference<>(weakReferenceObject);
System.out.println(weakReference.get());
System.gc();
System.out.println(weakReference.get());
weakReferenceObject = null;
System.gc();
System.out.println(weakReference.get());
}
public static class WeakReferenceObject{
@Override
protected void finalize() throws Throwable {
System.out.println("finalize ");
}
}
// output
WeakReferenceDemo$WeakReferenceObject@4d591d15
com.daxiyan.study.base.concurrent.WeakReferenceDemo$WeakReferenceObject@4d591d15
null
finalize
虚引用
虚引用顾名思义,就是形同虚设。与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收。
ThreadLocal的弱引用
// Entry的构造方法中可以看出ThreadLocal 作为WeakReference的referent。那么在下一次垃圾回收时Entry中的ThreadLocal会被回收掉。
内存泄漏
这里的内存泄漏指的是 无用对象(不再使用的对象)持续占有内存或无用对象的内存得不到及时释放,从而造成内存空间的浪费称为内存泄漏。
当ThreadLocal变量和 Entry的Key ThreadLocal 弱引用被释放后,但是Entry的value还没被释放,并且不再使用,这时就导致了内存泄漏。
ThreadLocal对Entry的key为null情况的优化
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;
}
// 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;
}
可以看到当调用get方法会触发key为null的Entry释放
内存泄漏的Demo
当threadLocal对象设为null时,value再也无法获取到,发生了内存泄漏,使用线程池确保线程不销毁,同时保证该线程不再被调用ThreadLocal.get,ThreadLocal.set方法,因为这两个方法中都存在 清除key为null 的Entry。
环境: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代码,控制台会打印java.lang.OutOfMemoryError: Java heap space。
threadLocal初始化代码 放在for循环里,for循环后不再被引用,在垃圾回收的时候将释放内存。因为线程词核心线程数100 大于需要的线程数80,不会触发在同一个线程调用get方法,所以导致ByteObject不会被释放而内存溢出。
如果将核心线程池改为1,此时无需remove,也不会存在内存溢出的情况,因为重复调用同一个线程的get方法,所以也会触发回收ByteObject。
在for循环开始初我sleep 100 毫秒,让垃圾回收有时间进行,否则,即使不注释掉remove也会导致内存溢出。
使用IDEA的visualgc插件观察
可以看到老年代一直保持在16M,内存没有泄露,所以没有内存溢出。
可以看到老年代一直保持在41M,由于内存泄漏,老年代一直释放不了,导致了内存溢出。
总结
使用ThreadLocal的完成后,要及时调用remove方法。
参考资料
ThreadLocal (Java Platform SE 8 )
关于Java中的WeakReference
ThreadLocal源码解读