/**
* 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;
}
}
在ThreadLocal源码中看到了WeakReference,所以来研究一下这个类。
package cn.chen.base;
import java.lang.ref.WeakReference;
public class WeakReferenceTest {
public static void main(String[] args) {
WeakReference<Object> weakReference = new WeakReference<Object>(new Object());
if(weakReference.get() != null) System.out.println("no gc");
System.gc();
if(weakReference.get() == null) System.out.println("gc");
else System.out.println("no gc");
}
}
no gc
gc
Process finished with exit code 0
我们在调用System.gc之后,WeakReference所引用的对象已经没有了,变成了一个空引用。(JVM规范并没有规定System.gc一定要发生GC,但是只考虑HotSport的话,HotSpot中执行System.gc一定会发生GC)
HotSpot实现
JVM_ENTRY_NO_ENV(void, JVM_GC(void))
JVMWrapper("JVM_GC");
if (!DisableExplicitGC) {
Universe::heap()->collect(GCCause::_java_lang_system_gc);
}
JVM_END
不同的GC算法,它所对应的heap是不同的,调用它的collect方法,就会对相应的heap执行垃圾回收。
在Java程序启动时,通过指定:-XX:+DisableExplicitGC
如果打开了这个选项,当应用程序调用System.gc时,就不会进行垃圾回收了。