• Java引用对象SoftReference WeakReference PhantomReference(二)


    四、Java对引用的分类

    级别

    什么时候被垃圾回收

    用途

    生存时间

    从来不会

    对象的一般状态

    JVM停止运行时终止

    在内存不足时

    对象简单?缓存

    内存不足时终止

    在垃圾回收时

    对象缓存

    gc运行后终止

    假象

    Unknown

    Unknown

    Unknown

    1、强引用:

    public static void main(String[] args) {

            MyDate date = new MyDate();

            System.gc();

    }

    解释:即使显式调用了垃圾回收,但是用于date是强引用,date没有被回收

    2、软引用:

    public static void main(String[] args) {

            SoftReference ref = new SoftReference(new MyDate());

            drainMemory(); // 让软引用工作

    }

    解释:在内存不足时,软引用被终止,等同于:

    MyDate date = new MyDate();

    //-------------------JVM决定运行-----------------

    If(JVM.内存不足()) {

             date = null;

             System.gc();

    }

    //-------------------------------------------------------------

    3、弱引用:

    public static void main(String[] args) {

            WeakReference ref = new WeakReference(new MyDate());

            System.gc(); // 让弱引用工作

    }

    解释:在JVM垃圾回收运行时,弱引用被终止,等同于:

    MyDate date = new MyDate();

    //------------------垃圾回收运行------------------

    public void WeakSystem.gc() {

             date = null;

             System.gc();

    }

    4、假象引用:

    public static void main(String[] args) {

            ReferenceQueue queue = new ReferenceQueue();

            PhantomReference ref = new PhantomReference(new MyDate(), queue);

            System.gc(); // 让假象引用工作

    }

    解释:假象引用,在实例化后,就被终止了,等同于:

    MyDate date = new MyDate();

    date = null;

    //-------终止点,在实例化后,不是在gc时,也不是在内存不足时--------


    http://hi.baidu.com/mynetbeans/blog/item/d72208fa8d63ac1ba9d31160.html
     

  • 相关阅读:
    MFiX做增量编译的时候不要删掉*.mod和*.inc文件
    Paraview教程
    origin生成直方图
    DEM轨迹后处理
    Zotero导入Markdown here插件
    origin把点图和线图放在一起
    mfix中输出DEM颗粒的固相速度到网格
    一个好用的ssh终端:MobaXterm
    GDB:从单线程调试到多线程调试(MFiX单步调试)
    操作系统概论-06
  • 原文地址:https://www.cnblogs.com/pony/p/1947941.html
Copyright © 2020-2023  润新知