背景
java引用分为强软弱虚引用
强引用
如果对象被强引用(就是我们理解的=),那么垃圾回收不会回收掉这个对象
public class Demo1 {
public static void main(String[] args) throws InterruptedException {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "java1", "java2");
System.gc();
System.out.println(list);
}
}
[java1, java2]
软引用
如果对象被软引用,但堆内存空间满了,那么垃圾回收会回收掉这个软引用对象
public class Demo2 {
public static void main(String[] args) {
SoftReference<byte[]> sf = new SoftReference<>(new byte[1024 * 1024 * 10]);
System.out.println(sf.get());
System.gc();
byte[] b = new byte[1024 * 1024 * 10];
System.out.println(sf.get());
}
}
[B@511baa65
null
弱引用
如果对象被弱引用,不管堆内存空间满没满,垃圾回收都会回收掉这个弱引用对象
public class Demo3 {
public static void main(String[] args) throws InterruptedException {
WeakReference<byte[]> reference = new WeakReference<>(new byte[1024 * 1024 * 10]);
System.out.println(reference.get());
System.gc();
System.out.println(reference.get());
}
}
[B@511baa65
null
虚引用
虚引用,顾名思义,就是形同虚设,与其他几种引用都不太一样,一个对象是否有虚引用的存在,完全不会对其生存时间构成影响,也无法通过虚引用来取得一个对象实例。
虚引用的主要作用是sun公司程序员跟踪对象垃圾回收的状态