zoukankan      html  css  js  c++  java
  • 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
     

  • 相关阅读:
    异步解决方案----Promise与Await
    多页应用 Webpack4 配置优化与踩坑记录
    左侧固定,右侧自适应的布局方式(新增评论区大佬教的方法)
    精读《Epitath 源码
    如何编写 Typescript 声明文件
    状态码具体解释
    LINQ体验(2)——C# 3.0新语言特性和改进(上篇)
    kafka教程
    double x = 10 ,y = 0;y = x % 2; 这个表达式正确吗?
    mongodb mapreduce使用总结
  • 原文地址:https://www.cnblogs.com/pony/p/1947941.html
Copyright © 2011-2022 走看看