软引用和虚引用

软引用指向的对象只在内存不足时被回收,而只被弱引用指向的对象在下一次GC时被回收

public class Test {
    public static void main(String[] agrs) {
        Object obj = new Object();
        SoftReference softReference = new SoftReference<>(obj);
        obj = null;

        System.gc();

        System.out.println("softObjTest, softReference : " + softReference.get());

        System.out.println("=================================");

        Object obj2 = new Object();
        WeakReference weakReference = new WeakReference<>(obj2);
        obj2 = null;//这里不置null,gc也不会回收

        System.gc();
        System.out.println("weakObjTest, weakReference : " + weakReference.get());
    }
}
 
 

运行结果:

softObjTest, softReference : java.lang.Object@74a14482
=================================
weakObjTest, weakReference : null

Process finished with exit code 0

从运行结果可见,SoftReference对象gc也不会回收,但是WeakReference执行gc时会被执行回收。

你可能感兴趣的:(软引用和虚引用)