Java中的四种引用类型 Strong, Soft, Weak And Phantom

1. 强引用(Strong References)

强引用类型是我们平时写代码的时候最常用的引用,而大部分人往往都会忽略这个概念,都成一种理所当然的事情了。 
接下来看看下面这个简单的例子:

public class Main {


    public static void main(String[] args) {

        //创建一个对象,new出来的对象都是分配在java堆中的
        Sample sample = new Sample();   //sample这个引用就是强引用

        sample = null;                  //将这个引用指向空指针,
                                        //那么上面那个刚new来的对象就没用任何其它有效的引用指向它了
                                        //也就说该对象对于垃圾收集器是符合条件的
                                        //因此在接下来某个时间点 GC进行收集动作的时候, 该对象将会被销毁,内存被释放

    }

}

class Sample {

}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

也可以画个简单的图理解一下: 
这里写图片描述

2. 软引用(Soft References)

软引用在java.lang.ref包中有与之对应的类java.lang.ref.SoftReference。 
重点: 被弱引用指向的对象不会被垃圾收集器收集(即使该对象没有强引用指向它),除非jvm使用内存不够了,才会对这类对象进行销毁,释放内存。举个简单的例子:

public class Main {

    public static void main(String[] args) {

        //创建一个对象,new出来的对象都是分配在java堆中的
        Sample sample = new Sample();   //sample这个引用就是强引用

        //创建一个软引用指向这个对象   那么此时就有两个引用指向Sample对象
        SoftReference<Sample> softRef = new SoftReference<Sample>(sample);

        //将强引用指向空指针 那么此时只有一个软引用指向Sample对象
        //注意:softRef这个引用也是强引用,它是指向SoftReference这个对象的
        //那么这个软引用在哪呢? 可以跟一下java.lang.Reference的源码 
        //private T referent; 这个才是软引用, 只被jvm使用
        sample = null;

        //可以重新获得Sample对象,并用一个强引用指向它
        sample = softRef.get();
    }

}

class Sample {

}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

有兴趣可以去看看Reference的源码。 
这里写图片描述

现在是不是想到了软引用的一个使用场景,它相比与强引用可以避免OOM。

现在可以简单的测试下 当jvm内存不足的情况下,软引用的回收情况。 
为了更快的看到结果,我限制了jvm的最大堆内存 -Xmx100m 为100m

public class Main {

    private static final List<Object> TEST_DATA = new LinkedList<>();


    public static void main(String[] args) throws InterruptedException {

        //创建一个对象,new出来的对象都是分配在java堆中的
        Sample sample = new Sample();   //sample这个引用就是强引用

        //创建一个软引用指向这个对象   那么此时就有两个引用指向Sample对象
        SoftReference<Sample> softRef = new SoftReference<Sample>(sample);

        //将强引用指向空指针 那么此时只有一个软引用指向Sample对象
        //注意:softRef这个引用也是强引用,它是指向SoftReference这个对象的
        //那么这个软引用在哪呢? 可以跟一下java.lang.Reference的源码
        //private T referent; 这个才是软引用, 只被jvm使用
        sample = null;

        //可以重新获得Sample对象,并用一个强引用指向它
        //sample = softRef.get();

        new Thread(){
            @Override
            public void run() {
                while (true) {
                    System.out.println(softRef.get());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    TEST_DATA.add(new byte[1024 * 1024 * 5]);
                }
            }
        }.start();

        Thread.currentThread().join();
    }

}

class Sample {
    private final byte[] data;

    public Sample() {
        data = new byte[1024 * 1024 * 10];
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

运行 输出结果:

example.Sample@3f580216
example.Sample@3f580216
example.Sample@3f580216
example.Sample@3f580216
example.Sample@3f580216
example.Sample@3f580216
example.Sample@3f580216
null
null
Exception in thread "Thread-0" java.lang.OutOfMemoryError: Java heap space
    at example.Main$1.run(Main.java:42)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

可以看到当jvm内存耗尽的时候,会将弱引用的对象进行回收 上面的例子的10m,且刚好还可以分配两次 5m一次 ,输出了两次null也证明了这一点

当然我们在创建软引用时,还可以传入ReferenceQueue,这个队列有啥用呢? 当jvm回收某个软引用对象之后会将该SoftReference对象(例子中的softRef对象)添加进这个队列,因此我们就知道这个对象啥时候被回收了,可以做一些我们想做的操作。

public SoftReference(T referent, ReferenceQueue<? super T> q) {
        super(referent, q);
        this.timestamp = clock;
}

Reference(T referent, ReferenceQueue<? super T> queue) {
        this.referent = referent;
        this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

还是举个简单的例子

public class Main {

    private static final List<Object> TEST_DATA = new LinkedList<>();

    private static final ReferenceQueue<Sample> QUEUE = new ReferenceQueue<>();


    public static void main(String[] args) {

        //创建一个对象,new出来的对象都是分配在java堆中的
        Sample sample = new Sample();   //sample这个引用就是强引用

        //创建一个软引用指向这个对象   那么此时就有两个引用指向Sample对象
        SoftReference<Sample> softRef = new SoftReference<Sample>(sample, QUEUE);

        //将强引用指向空指针 那么此时只有一个软引用指向Sample对象
        //注意:softRef这个引用也是强引用,它是指向SoftReference这个对象的
        //那么这个软引用在哪呢? 可以跟一下java.lang.Reference的源码
        //private T referent; 这个才是软引用, 只被jvm使用
        sample = null;

        //可以重新获得Sample对象,并用一个强引用指向它
        //sample = softRef.get();

        new Thread(){
            @Override
            public void run() {
                while (true) {
                    System.out.println(softRef.get());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                    TEST_DATA.add(new byte[1024 * 1024 * 5]);
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                while (true) {
                    Reference<? extends Sample> poll = QUEUE.poll();
                    if (poll != null) {
                        System.out.println("--- 软引用对象被jvm回收了 ---- " + poll);
                        System.out.println("--- 回收对象 ---- " + poll.get());
                    }
                }
            }
        }.start();

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            System.exit(1);
        }
    }

}

class Sample {
    private final byte[] data;

    public Sample() {
        data = new byte[1024 * 1024 * 10];
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

运行 输出结果:

example.Sample@2a3c142c
example.Sample@2a3c142c
example.Sample@2a3c142c
example.Sample@2a3c142c
example.Sample@2a3c142c
example.Sample@2a3c142c
example.Sample@2a3c142c
--- 软引用对象被jvm回收了 ---- java.lang.ref.SoftReference@306d3b64
null
--- 回收对象 ---- null
null
Exception in thread "Thread-0" java.lang.OutOfMemoryError: Java heap space
    at example.Main$1.run(Main.java:47)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
3. 弱引用(Weak References)

弱引用会被jvm忽略,也就说在GC进行垃圾收集的时候,如果一个对象只有弱引用指向它,那么和没有引用指向它是一样的效果,jvm都会对它就行果断的销毁,释放内存。其实这个特性是很有用的,jdk也提供了java.util.WeakHashMap这么一个key为弱引用的Map。比如某个资源对象你要释放(比如 db connection), 但是如果被其它map作为key强引用了,就无法释放,被jvm收集。

来个简单的例子:

public class Main {

    private static final List<Object> TEST_DATA = new LinkedList<>();

    private static final ReferenceQueue<Sample> QUEUE = new ReferenceQueue<>();


    public static void main(String[] args) {

        //创建一个对象,new出来的对象都是分配在java堆中的
        Sample sample = new Sample();   //sample这个引用就是强引用

        //创建一个弱引用指向这个对象   那么此时就有两个引用指向Sample对象
        //SoftReference<Sample> softRef = new SoftReference<Sample>(sample, QUEUE);
        WeakReference<Sample> weakRef = new WeakReference<Sample>(sample, QUEUE);
        //将强引用指向空指针 那么此时只有一个弱引用指向Sample对象
        //注意:softRef这个引用也是强引用,它是指向SoftReference这个对象的
        //那么这个弱引用在哪呢? 可以跟一下java.lang.Reference的源码
        //private T referent; 这个才是弱引用, 只被jvm使用
        sample = null;

        //可以重新获得Sample对象,并用一个强引用指向它
        //sample = softRef.get();

        new Thread(){
            @Override
            public void run() {
                while (true) {
                    System.out.println(weakRef.get());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                    TEST_DATA.add(new byte[1024 * 1024 * 5]);
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                while (true) {
                    Reference<? extends Sample> poll = QUEUE.poll();
                    if (poll != null) {
                        System.out.println("--- 弱引用对象被jvm回收了 ---- " + poll);
                        System.out.println("--- 回收对象 ---- " + poll.get());
                    }
                }
            }
        }.start();

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            System.exit(1);
        }
    }

}

class Sample {
    private final byte[] data;

    public Sample() {
        data = new byte[1024 * 1024 * 10];
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

运行 输出结果:

example.Sample@234c0f50
example.Sample@234c0f50
--- 弱引用对象被jvm回收了 ---- java.lang.ref.WeakReference@16fea746
--- 回收对象 ---- null
null
null
null
null
null
null
null
Exception in thread "Thread-0" java.lang.OutOfMemoryError: Java heap space
    at example.Main$1.run(Main.java:47)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

从结果中可以清晰的看到弱引用对象并不需要在jvm耗尽内存的情况下才进行回收, 是可以随时回收的。

4. 虚幻引用(Phantom References)

虚幻应用和弱引用的回收机制差不多,都是可以被随时回收的。但是不同的地方是,它的构造方法必须强制传入ReferenceQueue,因为在jvm回收前(重点: 对,就是回收前,软引用和弱引用都是回收后),会将PhantomReference对象加入ReferenceQueue中; 还有一点就是PhantomReference.get()方法永远返回空,不管对象有没有被回收。

源码: java.lang.ref.PhantomReference
    /**
     * Returns this reference object's referent.  Because the referent of a
     * phantom reference is always inaccessible, this method always returns
     * <code>null</code>.
     *
     * @return  <code>null</code>
     */
    public T get() {
        return null;
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

来个例子看看:

public class Main {

    private static final List<Object> TEST_DATA = new LinkedList<>();

    private static final ReferenceQueue<Sample> QUEUE = new ReferenceQueue<>();


    public static void main(String[] args) {

        Sample sample = new Sample();

        PhantomReference<Sample> phantomRef = new PhantomReference<>(sample, QUEUE);
        sample = null;

        new Thread(){
            @Override
            public void run() {
                while (true) {
                    System.out.println(phantomRef.get());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                    TEST_DATA.add(new byte[1024 * 1024 * 5]);
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                while (true) {
                    Reference<? extends Sample> poll = QUEUE.poll();
                    if (poll != null) {
                        System.out.println("--- 虚幻引用对象被jvm回收了 ---- " + poll);
                        System.out.println(poll.isEnqueued());
                        System.out.println("--- 回收对象 ---- " + poll.get());
                    }
                }
            }
        }.start();

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            System.exit(1);
        }
    }

}

class Sample {
    private final byte[] data;

    public Sample() {
        data = new byte[1024 * 1024 * 10];
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

运行 结果:

null
null
--- 虚幻引用对象被jvm回收了 ---- java.lang.ref.PhantomReference@40788638
false
--- 回收对象 ---- null
null
null
null
null
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值