Java-Four reference types and their recycling mechanism

The first type of strong reference

public class StrongReference {
    
    
    public static void main(String[] args) {
    
    
        //强引用
        StrongReference strongReference = new StrongReference();
        /**
        直接new出来的话就是强引用类型
        strongReference指向 一个new出来的 放在堆内存里的StrongReference对象
        当一个实例对象具有强引用时 垃圾回收器不会回收该对象 当内存不足时 宁愿抛出OutOfMemeryError异常也不会通过回收强引用的对象
         */
    }
}

More commonly used is the hardest reference
The second type of soft reference

public static void main(String[] args) {
    
    
        Object obj = new Object();
        SoftReference<Object> sf = new SoftReference<Object>(obj);
        obj = null;
        sf.get();
        /**
         * 软引用是除了强引用外,最强的引用类型。可以通过java.lang.ref.SoftReference使用软引用。
         * 一个持有软引用的对象,不会被JVM很快回收,JVM会根据当前堆的使用情况来判断何时回收。
         * 当堆使用率临近阈值时,才会去回收软引用的对象。因此,软引用可以用于实现对内存敏感的高速缓存。
         * SoftReference的特点是它的一个实例保存对一个Java对象的软引用
         */
    }

Compared with the strong reference, it is softer. The third weak reference will be recycled when the jvm memory is not available.

public static void main(String[] args) {
    
    
        Object obj = new Object();
        WeakReference<Object> wf = new WeakReference<Object>(obj);
        obj = null;
        wf.get();
        /**
         * 弱引用是一种比软引用较弱的引用类型。在系统GC时,只要发现弱引用,不管系统堆空间是否足够,都会将对象进行回收。
         */
    }

gc will recycle when found, very weak. The
fourth phantom reference

public static void main(String[] args) {
    
    
        Object obj = new Object();
        ReferenceQueue<? super Object> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Object> pf = new PhantomReference<Object>(obj,referenceQueue);
        obj=null;
        pf.get();
        /**
         * 虚引用是所有类型中最弱的一个。一个持有虚引用的对象和没有引用几乎是一样的,随时可能被垃圾回收器回收,
         * 当试图通过虚引用的get()方法取得强引用时,总是会失败。并且虚引用必须和引用队列一起使用,
         * 它的作用在于检测对象是否已经从内存中删除,跟踪垃圾回收过程。
         */
    }

Guess you like

Origin blog.csdn.net/qq_36008278/article/details/115075360