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
  • 相关阅读:
    抓包工具—Fiddler
    vue 统一注册公共组件
    vscode 配置 eslint 自动格式化
    vue axios http 请求 响应拦截
    vue实现菜单权限控制
    webpack之深入浅出externals
    webpack之前端性能优化(史上最全,不断更新中。。。)
    webpack插件url-loader使用规范
    移动端布局最佳实践(viewport+rem)
    本地更新代码同步至github仓库
  • 原文地址:https://www.cnblogs.com/wangzhanhua/p/10436877.html
Copyright © 2011-2022 走看看