1、强引用
public class TestPerson {
public static final int _4MB = 4 * 1024*1024;
public static void main(String[] args) {
// for(int i = 0; i < 5; i++) {
// list.add(new byte[_4MB]);
// }
//list时一个强引用,其引用一个ArrayList对象
List<SoftReference<byte[]>> list = new ArrayList<>();
for(int i = 0; i < 5; i++) {
//soft是一个强引用,引用 SoftReference对象,SoftReference对象软引用一个byte数组对象,即soft相当于通过一个软引用对象引用byte数组
SoftReference<byte[]> soft = new SoftReference<>(new byte[_4MB]);
list.add(soft);
System.out.println(soft.get());
System.out.println(list.size());
}
for(SoftReference<byte[]> b: list) {
System.out.println(b.get());
}
}
}
注释掉的代码执行后会出现内存溢出错误,而通过软引用的的list数组在循环五次后不会出现内存溢出的现象,但是前四个byte数组对象将会被回收掉。
引用队列的作用就是在软引用的对象byte数组被回收后,soft引用的一个SoftReference对象被回收掉。
配合引用队列使用。
public class TestPerson {
public static final int _4MB = 4 * 1024*1024;
public static void main(String[] args) throws InterruptedException {
// for(int i = 0; i < 5; i++) {
// list.add(new byte[_4MB]);
// }
List<SoftReference<byte[]>> list = new ArrayList<>();
ReferenceQueue<byte[]> queue = new ReferenceQueue<>();
for(int i = 0; i < 5; i++) {
SoftReference<byte[]> soft = new SoftReference<>(new byte[_4MB],queue);
list.add(soft);
System.out.println(soft.get());
System.out.println(list.size());
}
Reference<? extends byte[]> poll = queue.poll();
while (poll != null) {
list.remove(poll);
poll = queue.poll();
}
System.out.println("=============");
for(SoftReference<byte[]> b: list) {
System.out.println(b.get());
}
}
}
3、弱引用
public class TestPerson {
public static final int _4MB = 4 * 1024*1024;
public static void main(String[] args) throws InterruptedException {
List<WeakReference<byte[]>> list = new ArrayList<>();
for(int i = 0; i < 5; i++) {
list.add(new WeakReference<byte[]>(new byte[_4MB]));
}
System.gc();
for (WeakReference<byte[]> b :list) {
System.out.println(b.get());
}
}
}
有System.gc()和没有输出时两种不同的结果。
因篇幅问题不能全部显示,请点此查看更多更全内容