zoukankan      html  css  js  c++  java
  • 强引用-软引用-弱引用

     

    • 强引用:普通的引用,强引用指向的对象不会被回收;
    • 软引用:仅有软引用指向的对象,只有发生gc且内存不足,才会被回收;
    • 弱引用:仅有弱引用指向的对象,只要发生gc就会被回收。

    看一个例子就明白强引用、软引用、弱引用的区别:

    package example.reference;
    
    import java.lang.ref.SoftReference;
    import java.lang.ref.WeakReference;
    
    public class WeakRefDemo {
    
        public static void main(String... args) {
    
            // all these objects have a strong reference
            Object a = new Object();
            Object b = new Object();
            Object c = new Object();
    
            // other references to these objects
            Object strongA = a;
            SoftReference<Object> softB = new SoftReference<>(b);
            WeakReference<Object> weakC = new WeakReference<>(c);
    
            // free the former strong references to these objects:
    
            // there is still a strong reference(strongA) to the first object
            a = null;
            // only a soft reference(softB) refers to the second object
            b = null;
            // only a weak reference(weakC) refers to the third object
            c = null;
    
            System.out.println("Before gc...");
            System.out.println(String.format("strongA = %s, softB = %s, weakC = %s", strongA, softB.get(), weakC.get()));
    
            System.out.println("Run GC...");
    
            System.gc();
    
            // object with only soft reference will be cleaned only if memory is not enough: 用来做缓存很不错
            // object with only weak reference will be cleaned after a gc operation:
            System.out.println("After gc...");
            System.out.println(String.format("strongA = %s, softB = %s, weakC = %s", strongA, softB.get(), weakC.get()));
        }
    }

    output:

    Before gc...
    strongA = java.lang.Object@3af49f1c, softB = java.lang.Object@19469ea2, weakC = java.lang.Object@13221655
    Run GC...
    After gc...
    strongA = java.lang.Object@3af49f1c, softB = java.lang.Object@19469ea2, weakC = null
  • 相关阅读:
    【POJ 3162】 Walking Race (树形DP-求树上最长路径问题,+单调队列)
    【POJ 2152】 Fire (树形DP)
    【POJ 1741】 Tree (树的点分治)
    【POJ 2486】 Apple Tree (树形DP)
    【HDU 3810】 Magina (01背包,优先队列优化,并查集)
    【SGU 390】Tickets (数位DP)
    【SPOJ 2319】 BIGSEQ
    【SPOJ 1182】 SORTBIT
    【HDU 5456】 Matches Puzzle Game (数位DP)
    【HDU 3652】 B-number (数位DP)
  • 原文地址:https://www.cnblogs.com/wangzhanhua/p/10436877.html
Copyright © 2011-2022 走看看