如果软引用所指的对象已经是null了,没有必要再把这四个软引用保留在list集合中。可以配合引用队列来完成软引用的回收。
public static void soft() { // list --> SoftReference --> byte[] List<SoftReference<byte[]>> list = new ArrayList<>(); ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue<>(); for (int i = 0; i < 5; i++) { SoftReference<byte[]> ref = new SoftReference<>(new byte[_4MB], referenceQueue); System.out.println(ref.get()); list.add(ref); System.out.println(list.size()); } Reference<? extends byte[]> poll = referenceQueue.poll(); while (poll != null) { list.remove(poll); poll = referenceQueue.poll(); } System.out.println("循环结束:" + list.size()); for (SoftReference<byte[]> ref : list) { System.out.println(ref.get()); } }
结果如下。
[B@7f31245a 1 [B@6d6f6e28 2 [B@135fbaa4 3 [B@45ee12a7 4 [B@330bedb4 5 循环结束:1 [B@330bedb4 Process finished with exit code 0