JVM垃圾回收-对象的四种引用

1. Java 技术允许使用 finalize() 方法在垃圾收集器将对象从内存中清除出去之前做必要的清理工作。

@Override
protected void finalize() throws Throwable{
    System.out.println(Thread.currentThread().getName()+"\t"+"---finalize method invoked....");
}
class MyObject {
    /**
     * 一般这个方法工作中不用,此处为了测试gc
     * @throws Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        System.out.println("------------- gc ,finalize() invoked");
    }
}


public class ReferenceDemo {
    public static void main(String[] args) {
        ReferenceQueue<MyObject> referenceQueue = new ReferenceQueue<>();
        PhantomReference<MyObject> phantomReference = new PhantomReference<>(new MyObject(), referenceQueue);
        System.out.println(phantomReference.get());

        List<byte[]> list = new ArrayList<>();

        new Thread(() -> {
            while (true) {
                list.add(new byte[1 * 1024 * 1024]);
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(phantomReference.get());
            }
        }, "t1").start();

        new Thread(() -> {
            while (true) {
                Reference<? extends MyObject> poll = referenceQueue.poll();
                if (poll != null) {
                    System.out.println("------有虚对象进入了队列");
                }
            }
        }, "t2").start();

        //暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void weakReference() {
        WeakReference<MyObject> weakReference = new WeakReference(new MyObject());
        System.out.println("gc before: " + weakReference.get());

        System.gc();//手动挡的方式开启Gc回收。
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("gc after: " + weakReference.get());
    }

    public static void softReference() {
        SoftReference<MyObject> softReference = new SoftReference<>(new MyObject());//软引用

        /*内存够用
        System.out.println("gc before内存够用: "+softReference);

        System.gc();//手动挡的方式开启Gc回收。
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println("gc after内存够用: "+softReference);*/

        //设置参数-Xms10m -Xmx10m
        System.out.println("gc before: " + softReference);

        try {
            byte[] bytes = new byte[9 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("-----gc after内存不够: " + softReference.get());
        }
    }

    public static void strongReference() {
        MyObject myObject = new MyObject();//默认,强引用,死了都不放手
        System.out.println("gc before: " + myObject);

        myObject = null;
        System.gc();//手动挡的方式开启Gc回收。
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("gc after: " + myObject);
    }
}

2. 强引用(默认支持模式)

  1. 强引用是我们最常见的普通对象引用,只要还有强引用指向一个对象,就能表明对象还“活着”,垃圾收集器不会碰这种对象。在Java中最常见的就是强引用,把一个对象赋给一个引用变量,这个引用变量就是一个强引用。当一个对象被强引用变量引用时,它处于可达状态,它是不可能被垃圾回收机制回收的,即使该对象以后永远都不会被用到JVM也不会回收。因此强引用是造成Java内存泄漏的主要原因之一。
  2. 对于一个普通的对象,如果没有其他的引用关系,只要超过了引用的作用域或者显式地将相应(强)引用赋值为 null,一般认为就是可以被垃圾收集的了(当然具体回收时机还是要看垃圾收集策略)。
public static void strongReference() {

    /*
           默认,强引用,死了都不放手
     */
    MyObject myObject = new MyObject();
    System.out.println("gc before: " + myObject);

    myObject = null;
    System.gc();//手动挡的方式开启Gc回收。
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("gc after: " + myObject);
}

3. 软引用

  1. 经常使用的缓存
  2. 软引用是一种相对强引用弱化了一些的引用,需要用java.lang.ref.SoftReference类来实现,可以让对象豁免一些垃圾收集。
  3. 软引用通常用在对内存敏感的程序中,比如高速缓存就有用到软引用,内存够用的时候就保留,不够用就回收

假如有一个应用需要读取大量的本地图片:

  1. 如果每次读取图片都从硬盘读取则会严重影响性能,
  2. 如果一次性全部加载到内存中又可能造成内存溢出。
  3. 用一个HashMap来保存图片的路径和相应图片对象关联的软引用之间的映射关系,在内存不足时,JVM会自动回收这些缓存图片对象所占用的空间,从而有效地避免了OOM的问题
Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
public static void softReference() {
    SoftReference<MyObject> softReference = new SoftReference<>(new MyObject());

    /*内存够用
    System.out.println("gc before内存够用: "+softReference);

    System.gc();
    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

    System.out.println("gc after内存够用: "+softReference);*/

    //设置参数-Xms10m -Xmx10m
    System.out.println("gc before: " + softReference);

    try {
        byte[] bytes = new byte[9 * 1024 * 1024];
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        System.out.println("-----gc after内存不够: " + softReference.get());
    }
}

4. 弱引用

  1. 不重要缓存
  2. 弱引用需要用java.lang.ref.WeakReference类来实现,它比软引用的生存期更短,
public static void weakReference() {
  WeakReference<MyObject> weakReference = new WeakReference(new MyObject());
  System.out.println("gc before: " + weakReference.get());

  System.gc();
  try {
    TimeUnit.SECONDS.sleep(1);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }

  System.out.println("gc after: " + weakReference.get());
}

5. 虚引用

  1. 虚引用需要java.lang.ref.PhantomReference类来实现。
  2. 顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。 如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收, 它不能单独使用也不能通过它访问对象,虚引用必须和引用队列 (ReferenceQueue)联合使用。
  3. 虚引用的主要作用是跟踪对象被垃圾回收的状态。 仅仅是提供了一种确保对象被 finalize以后,做某些事情的机制。 PhantomReference的get方法总是返回null,因此无法访问对应的引用对象。
  4. 虚引用的主要作用是跟踪对象被垃圾回收的状态。 仅仅是提供了一种确保对象被 finalize以后,做某些事情的机制。 PhantomReference的get方法总是返回null,因此无法访问对应的引用对象。
ReferenceQueue<MyObject> referenceQueue = new ReferenceQueue<>();
PhantomReference<MyObject> phantomReference = new PhantomReference<>(new MyObject(), referenceQueue);
System.out.println(phantomReference.get());

List<byte[]> list = new ArrayList<>();

new Thread(() -> {
    while (true) {
        list.add(new byte[1 * 1024 * 1024]);
        try {TimeUnit.MILLISECONDS.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
        System.out.println(phantomReference.get());
    }
}, "t1").start();

new Thread(() -> {
    while (true) {
        Reference<? extends MyObject> poll = referenceQueue.poll();
        if (poll != null) {
            System.out.println("------有虚对象进入了队列");
        }
    }
}, "t2").start();

try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}
  • 20
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值