持有引用
一节,书中讲述了有关 java.lang.ref 包下的 Reference 类Java 新手,查了些资料还是没有头绪,实在不行的话我换个 JDK 试下...
以下是原书部分样例代码
package sust.p600.p519;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
/**
* Created by SunnyGrocery on 2019/11/17 18:05
*/
public class References {
private static ReferenceQueue<VeryBig> referenceQueue = new ReferenceQueue<>();
public static void main(String[] args) {
int size = 10;
LinkedList<SoftReference<VeryBig>> referenceLinkedList = new LinkedList<>();
for (int i = 0; i < size; i++) {
referenceLinkedList.add(new SoftReference<>(
new VeryBig("Soft:" + i),
referenceQueue));
System.out.println("Just created:" + referenceLinkedList.getLast());
checkQueue();
}
LinkedList<WeakReference<VeryBig>> referenceLinkedList1 = new LinkedList<>();
for (int i = 0; i < size; i++) {
referenceLinkedList1.add(new WeakReference<>(
new VeryBig("Weak:" + i),
referenceQueue));
System.out.println("Just created:" + referenceLinkedList1.getLast());
checkQueue();
}
}
private static void checkQueue() {
Reference<? extends VeryBig> reference = referenceQueue.poll();
if (reference != null) {
System.out.println("In queue: " + reference.get());
}
}
}
class VeryBig {
private static final int SiZE = 10000;
private long[] la = new long[SiZE];
private String ident;
public VeryBig(String id) {
ident = id;
}
@Override
public String toString() {
return "id = " + ident;
}
protected void finalize() {
System.out.println("Finalizing:" + ident);
}
}
输出
Just created:java.lang.ref.SoftReference@677327b6
Just created:java.lang.ref.SoftReference@14ae5a5
Just created:java.lang.ref.SoftReference@7f31245a
Just created:java.lang.ref.SoftReference@6d6f6e28
Just created:java.lang.ref.SoftReference@135fbaa4
Just created:java.lang.ref.SoftReference@45ee12a7
Just created:java.lang.ref.SoftReference@330bedb4
Just created:java.lang.ref.SoftReference@2503dbd3
Just created:java.lang.ref.SoftReference@4b67cf4d
Just created:java.lang.ref.SoftReference@7ea987ac
Just created:java.lang.ref.WeakReference@12a3a380
Just created:java.lang.ref.WeakReference@29453f44
Just created:java.lang.ref.WeakReference@5cad8086
Just created:java.lang.ref.WeakReference@6e0be858
Just created:java.lang.ref.WeakReference@61bbe9ba
Just created:java.lang.ref.WeakReference@610455d6
Just created:java.lang.ref.WeakReference@511d50c0
Just created:java.lang.ref.WeakReference@60e53b93
Just created:java.lang.ref.WeakReference@5e2de80c
Just created:java.lang.ref.WeakReference@1d44bcfa
结果中没有 checkQueue
中当 reference != null
时的输出
也就是说, referenceQueue.poll()
一直为空
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.