WeakReference

 

/**

* 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时,就不会进行垃圾回收了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值