学习笔记:java四种引用类型

2020-02-28  本文已影响0人  大力papa

本文仅供学习交流使用,侵权必删。
不作商业用途,转载请注明出处。

强引用

软引用

/*
-Xms5M -Xmx5M
*/
 public static void main(String[] args) throws InterruptedException {
        SoftReference<byte[]> sr = new SoftReference<>(new byte[1024 * 1024 * 2]);
        System.out.println("softRef get: "+sr.get());//没有被回收
        byte[] sr2 = new byte[1024 * 1024 * 2];
        System.out.println("softRef get: "+sr.get());//已经被回收
        System.out.println("normalRef :"+sr2);

    }

弱引用

public static void main(String[] args) throws InterruptedException {
        WeakReference wr = new WeakReference<>(new Object());
        System.gc();
        System.out.println(wr.get());//null
    }

虚引用

  private static final ReferenceQueue QUEUE = new ReferenceQueue<>();
    private static List lst = new LinkedList<byte[]>();

    static class Garbage {
        public Garbage() {}
    }
        public static void main(String[] args) {

            PhantomReference pr = new PhantomReference<Object>(new Garbage(), QUEUE);
            System.out.println("PhantomReference::get "+pr.get());

            new Thread(() -> {
                for (int i = 0; i < 5; i++) {
                    lst.add(new byte[1024 * 1024 * 1]);
                }
            }).start();

            new Thread(() -> {
                for (; ; ) {
                    Reference<? extends Garbage> ref;
                    if ((ref = QUEUE.poll()) != null) {
                        System.out.println("PhantomReference Garbage 被回收:" + ref);
                        System.out.println("PhantomReference::get "+ref.get());
                    }
                }
            }).start();
        }
上一篇 下一篇

猜你喜欢

热点阅读