java List是强引用吗_Java中的四种引用类型:强引用、软引用、弱引用和虚引用...

在Java中是由JVM负责内存的分配和回收,这是它的优点(简化编程者的工作,不需要像C语言那样去手动操作内存),但同时也是它的缺点(不够灵活,垃圾回收对于编程者来说是不可控的)。

在JDK1.2以前,如果一个对象不被任何变量引用,则程序无法再次使用这个对象,这个对象最终会被GC(GabageCollection:垃圾回收)。但是如果之后可能还会用到这个对象,就只能去新建一个了,这其实就降低了JVM性能,没有达到最大的优化策略。

因此,从JDK1.2开始,提供了四种类型的引用:强引用(StrongReference)、软引用(SoftReference)、弱引用(WeakReference)和虚引用(PhantomReference)。主要有两个目的:可以在代码中决定某些对象的生命周期;

优化JVM的垃圾回收机制。

关于GC

什么是 GC(GabageCollection)?

GC通常是运行在一个独立的、优先级比较低的线程中,实时监测并释放“无效”的内存。

什么是“无效"的内存单元?

一般GC采用引用计数法来判断一个内存单元(一个变量)是否是无效的内存。

引用计数法(引用计数法只是GC中一种常用的方法,还会用到年代方法等)是指一个变量或一块内存当前被引用的次数,如果引用次数为0,则表示这个变量或这块内存未被引用,因此GC“有可能”去释放它

,为什么说有可能?首先GC运行在一个独立的、优先级比较低的线程中,其次GC回收的具体工作也是比较复杂的,比如说需要释放大量内存的时候,而CPU资源又相对紧张,GC可能会选择性地释放一些内存资源,具体回收方法取决于GC内部的算法。

四种引用类型

强引用

强引用是最普遍的引用,如果一个对象具有强引用,垃圾回收器不会回收该对象,当内存空间不足时,JVM 宁愿抛出 OutOfMemoryError异常;只有当这个对象没有被引用时,才有可能会被回收。package com.lzumetal.jvmtest;import java.util.ArrayList;import java.util.List;public class StrongReferenceTest {    static class BigObject {        private Byte[] bytes = new Byte[1024 * 1024];

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

List list = new ArrayList<>();        while (true) {

BigObject obj = new BigObject();

list.add(obj);

}

}

}

BigObject obj = new BigObject()创建的这个对象时就是强引用,上面的main方法最终将抛出OOM异常:Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

at com.lzumetal.jvm.StrongReferenceTest$BigObject.(StrongReferenceTest.java:9)

at com.lzumetal.jvm.StrongReferenceTest.main(StrongReferenceTest.java:16)

软引用

如果一个对象只具有软引用,则当内存空间足够,垃圾回收器就不会回收它。

当内存空间不足了,就会回收该对象。

JVM会优先回收长时间闲置不用的软引用的对象,对那些刚刚构建的或刚刚使用过的“新”软引用对象会尽可能保留。

如果回收完还没有足够的内存,才会抛出内存溢出异常。只要垃圾回收器没有回收它,该对象就可以被程序使用。

软引用是用来描述一些有用但并不是必需的对象,适合用来实现缓存(比如浏览器的‘后退’按钮使用的缓存),内存空间充足的时候将数据缓存在内存中,如果空间不足了就将其回收掉。

软引用在Java中用java.lang.ref.SoftReference类来表示。为了方便测试,在下面这个示例中我设置了JVM的内存为8M,在IDEA的Run——>EditConfigiratons中设置参数:-Xms8m

-Xmx8m -XX:+PrintGCDetails

AAffA0nNPuCLAAAAAElFTkSuQmCC

代码:package com.lzumetal.jvmtest;import java.lang.ref.SoftReference;public class SoftReferenceTest {    static class Person {        private String name;        private Byte[] bytes = new Byte[1024 * 1024];        public Person(String name) {            this.name = name;

}

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

Person person = new Person("张三");

SoftReference softReference = new SoftReference<>(person);

person = null;  //去掉强引用,new Person("张三")的这个对象就只有软引用了

System.gc();

Thread.sleep(1000);

System.err.println("软引用的对象 ------->" + softReference.get());

}

}

运行main方法,控制台输出:[GC (Allocation Failure) [PSYoungGen: 1536K->504K(2048K)] 1536K->748K(7680K), 0.0118019 secs] [Times: user=0.08 sys=0.00, real=0.01 secs]

[GC (System.gc()) [PSYoungGen: 1005K->496K(2048K)] 5346K->4868K(7680K), 0.0025626 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]

[Full GC (System.gc()) [PSYoungGen: 496K->0K(2048K)] [ParOldGen: 4372K->4773K(5632K)] 4868K->4773K(7680K), [Metaspace: 3466K->3466K(1056768K)], 0.0083134 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]

软引用的对象 ------->com.lzumetal.jvmtest.SoftReferenceTest$Person@6d6f6e28

Heap

PSYoungGen      total 2048K, used 45K [0x00000000ffd80000, 0x0000000100000000, 0x0000000100000000)

eden space 1536K, 2% used [0x00000000ffd80000,0x00000000ffd8b7b8,0x00000000fff00000)

from space 512K, 0% used [0x00000000fff80000,0x00000000fff80000,0x0000000100000000)

to   space 512K, 0% used [0x00000000fff00000,0x00000000fff00000,0x00000000fff80000)

ParOldGen       total 5632K, used 4773K [0x00000000ff800000, 0x00000000ffd80000, 0x00000000ffd80000)

object space 5632K, 84% used [0x00000000ff800000,0x00000000ffca9498,0x00000000ffd80000)

Metaspace       used 3474K, capacity 4500K, committed 4864K, reserved 1056768K  class space    used 382K, capacity 388K, committed 512K, reserved 1048576K

虽然调用System.gc()后JVM并不一定会立刻进行GC操作,但从上面这段输出可以看到JVM确实进行了GC,但是软引用的对象并没有被回收掉,说明现在内存空间还足够,JVM暂时还不会回收软引用的对象。

把main方法改成如下:public static void main(String[] args) throws InterruptedException {

Person person = new Person("张三");

SoftReference softReference = new SoftReference<>(person);

person = null;//去掉强引用,new Person("张三")的这个对象就只有软引用了

Person anotherPerson = new Person("李四");

Thread.sleep(1000);

System.err.println("软引用的对象 ------->" + softReference.get());

}

因为这里JVM内存只有8M,没有足够的空间同时保留两个Person对象(我已经测试过了:new两个强引用的Person对象就会报OOM),所以当我再new Person("李四")时,也是会触发JVM的GC的,同时因为前面的new Person("张三")只有软引用了,它会被回收掉。[GC (Allocation Failure) [PSYoungGen: 1536K->504K(2048K)] 1536K->664K(7680K), 0.0009884 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]

[GC (Allocation Failure) [PSYoungGen: 1006K->504K(2048K)] 5262K->4848K(7680K), 0.0077414 secs] [Times: user=0.06 sys=0.00, real=0.01 secs]

[GC (Allocation Failure) [PSYoungGen: 504K->504K(2048K)] 4848K->4872K(7680K), 0.0017661 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]

[Full GC (Allocation Failure) [PSYoungGen: 504K->0K(2048K)] [ParOldGen: 4368K->4773K(5632K)] 4872K->4773K(7680K), [Metaspace: 3465K->3465K(1056768K)], 0.0201011 secs] [Times: user=0.08 sys=0.00, real=0.02 secs]

[GC (Allocation Failure) [PSYoungGen: 0K->0K(2048K)] 4773K->4773K(7680K), 0.0039905 secs] [Times: user=0.06 sys=0.00, real=0.00 secs]

[Full GC (Allocation Failure) [PSYoungGen: 0K->0K(2048K)] [ParOldGen: 4773K->659K(5632K)] 4773K->659K(7680K), [Metaspace: 3465K->3465K(1056768K)], 0.0103549 secs] [Times: user=0.00 sys=0.00, real=0.01 secs]

软引用的对象 ------->nullHeap

PSYoungGen      total 2048K, used 45K [0x00000000ffd80000, 0x0000000100000000, 0x0000000100000000)

eden space 1536K, 2% used [0x00000000ffd80000,0x00000000ffd8b7b8,0x00000000fff00000)

from space 512K, 0% used [0x00000000fff80000,0x00000000fff80000,0x0000000100000000)

to   space 512K, 0% used [0x00000000fff00000,0x00000000fff00000,0x00000000fff80000)

ParOldGen       total 5632K, used 4755K [0x00000000ff800000, 0x00000000ffd80000, 0x00000000ffd80000)

object space 5632K, 84% used [0x00000000ff800000,0x00000000ffca4c80,0x00000000ffd80000)

Metaspace       used 3473K, capacity 4500K, committed 4864K, reserved 1056768K  class space    used 382K, capacity 388K, committed 512K, reserved 1048576K

ReferenceQueue

SoftReference对象是用来保存软引用,但它同时也是一个Java对象。所以,当软可及对象被回收之后,虽然这个SoftReference对象的get()方法返回null,但SoftReference对象本身并不是null,而此时这个SoftReference对象已经不再具有存在的价值,需要一个适当的清除机制,避免大量SoftReference对象带来的内存泄漏。

在java.lang.ref包里还提供了ReferenceQueue。如果在创建SoftReference对象的时候,使用了一个ReferenceQueue对象作为参数提供给SoftReference的构造方法,如:Person person = new Person("张三");

ReferenceQueue queue = new ReferenceQueue<>();

SoftReference softReference = new SoftReference(person, queue);

在SoftReference所软引用的Person对象被垃圾回收时,JVM会先将softReference对象添加到ReferenceQueue这个队列中。当我们调用ReferenceQueue的poll()方法,如果这个队列中不是空队列,那么将返回并移除前面添加的那个Reference对象。

还是上面的那个例子,测试代码:public static void main(String[] args) throws InterruptedException {

Person person = new Person("张三");

ReferenceQueue queue = new ReferenceQueue<>();

SoftReference softReference = new SoftReference(person, queue);

person = null;//去掉强引用,new Person("张三")的这个对象就只有软引用了

Person anotherPerson = new Person("李四");

Thread.sleep(1000);

System.err.println("软引用的对象 ------->" + softReference.get());

Reference softPollRef = queue.poll();        if (softPollRef != null) {

System.err.println("SoftReference对象中保存的软引用对象已经被GC,准备清理SoftReference对象");            //清理softReference

}

}

控制台输出:[GC (Allocation Failure) [PSYoungGen: 1536K->504K(2048K)] 1536K->728K(7680K), 0.0022378 secs] [Times: user=0.03 sys=0.05, real=0.00 secs]

[GC (Allocation Failure) [PSYoungGen: 1036K->504K(2048K)] 5356K->4840K(7680K), 0.0027540 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]

[GC (Allocation Failure) [PSYoungGen: 504K->504K(2048K)] 4840K->4840K(7680K), 0.0048557 secs] [Times: user=0.00 sys=0.00, real=0.01 secs]

[Full GC (Allocation Failure) [PSYoungGen: 504K->0K(2048K)] [ParOldGen: 4336K->4774K(5632K)] 4840K->4774K(7680K), [Metaspace: 3468K->3468K(1056768K)], 0.0087802 secs] [Times: user=0.11 sys=0.00, real=0.01 secs]

[GC (Allocation Failure) [PSYoungGen: 0K->0K(2048K)] 4774K->4774K(7680K), 0.0005462 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]

[Full GC (Allocation Failure) [PSYoungGen: 0K->0K(2048K)] [ParOldGen: 4774K->659K(5632K)] 4774K->659K(7680K), [Metaspace: 3468K->3468K(1056768K)], 0.0104794 secs] [Times: user=0.05 sys=0.02, real=0.01 secs]

软引用的对象 ------->nullSoftReference对象中保存的软引用对象已经被GC,准备清理SoftReference对象

Heap

PSYoungGen      total 2048K, used 45K [0x00000000ffd80000, 0x0000000100000000, 0x0000000100000000)

eden space 1536K, 2% used [0x00000000ffd80000,0x00000000ffd8b7b8,0x00000000fff00000)

from space 512K, 0% used [0x00000000fff80000,0x00000000fff80000,0x0000000100000000)

to   space 512K, 0% used [0x00000000fff00000,0x00000000fff00000,0x00000000fff80000)

ParOldGen       total 5632K, used 4755K [0x00000000ff800000, 0x00000000ffd80000, 0x00000000ffd80000)

object space 5632K, 84% used [0x00000000ff800000,0x00000000ffca4d70,0x00000000ffd80000)

Metaspace       used 3476K, capacity 4500K, committed 4864K, reserved 1056768K  class space    used 382K, capacity 388K, committed 512K, reserved 1048576K

弱引用

弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期,它只能生存到下一次垃圾收集发生之前。当垃圾回收器扫描到只具有弱引用的对象时,无论当前内存空间是否足够,都会回收它。不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。

弱引用也可以和一个引用队列(ReferenceQueue)联合使用。

使用场景:一个对象只是偶尔使用,希望在使用时能随时获取,但也不想影响对该对象的垃圾收集,则可以考虑使用弱引用来指向该对象。

参考上面的代码示例,测试弱引用:public static void main(String[] args) throws InterruptedException {

Person person = new Person("张三");

ReferenceQueue queue = new ReferenceQueue<>();

WeakReference weakReference = new WeakReference(person, queue);

person = null;//去掉强引用,new Person("张三")的这个对象就只有软引用了

System.gc();

Thread.sleep(1000);

System.err.println("弱引用的对象 ------->" + weakReference.get());

Reference weakPollRef = queue.poll();   //poll()方法是有延迟的

if (weakPollRef != null) {

System.err.println("WeakReference对象中保存的弱引用对象已经被GC,下一步需要清理该Reference对象");            //清理softReference

} else {

System.err.println("WeakReference对象中保存的软引用对象还没有被GC,或者被GC了但是获得对列中的引用对象出现延迟");

}

}

虚引用

与其他三种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收。

虚引用主要用来跟踪对象被垃圾回收的活动。虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列(ReferenceQueue)联合使用。当垃

圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。Object object = new Object();

ReferenceQueue queue = new ReferenceQueue ();

PhantomReference pr = new PhantomReference (object, queue);

程序可以通过判断引用队列中是 否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。程序如果发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。

在实际程序设计中一般很少使用弱引用与虚引用,使用软引用的情况较多,这是因为软引用可以加速JVM对垃圾内存的回收速度,可以维护系统的运行安全,防止内存溢出(OutOfMemory)等问题的产生。

本文代码已上传至我的GitHub

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值