Java WeakReference

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/future234/article/details/80732741

关于WeakReference的定义引用维基百科定义

在计算机程序设计中,弱引用与强引用相对,是指不能确保其引用的对象不会被垃圾回收器回收的引用。一个对象若只被弱引用所引用,则被认为是不可访问(或弱可访问)的,并因此可能在任何时刻被回收。一些配有垃圾回收机制的语言,如Java、C#、Python、Perl、Lisp等都在不同程度上支持弱引用。

1. WeakReference引用的对象什么时候被回收?

WeakReference所引用的对象,会在垃圾回收发生时被回收,但是是有前提条件的。我们知道垃圾回收分为minorGC 和 majorGC。如果发生若了minorGC,而弱引用指向的对象,只有弱引用,没有其他引用,而且对象在新生代中,才会被回收掉。如果发生了majorGc,如果对象只被弱引用引用,对象会被回收掉。

 WeakReference<String> weakReference = new WeakReference<String>(new String("Hello WeakReference"));
        System.out.println(weakReference.get());
        System.gc();
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(weakReference.get());
输出结果如下

Hello WeakReference
[GC (System.gc())  883K->472K(9728K), 0.0008970 secs]
[Full GC (System.gc())  472K->381K(9728K), 0.0125556 secs]
null

如上证实了发生gc 只有WeakReference指向的对象会被回收掉

2.考虑这种情况呢
 WeakReference<String> weakReference = new WeakReference<String>("Hello WeakReference");
        System.out.println(weakReference.get());
        System.gc();
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(weakReference.get());
输出结果如下

Hello WeakReference
[GC (System.gc())  887K->504K(9728K), 0.0124477 secs]
[Full GC (System.gc())  504K->381K(9728K), 0.0300315 secs]
Hello WeakReference

为什么这种情况下没有被回收掉呢?原因是”Hello WeakReference”是分配在常量池中,并不是分配在java堆中java gc并不会回收掉

猜你喜欢

转载自blog.csdn.net/future234/article/details/80732741