持有引用
一节,书中讲述了有关 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()
一直为空
1
zhady009 2019-11-17 23:34:48 +08:00 1
堆大小多大? 我测试-Xmx3M 才能取出 或者可以加大 VeryBig 中的数组大小
|
2
SunnyGrocery OP @zhady009 很大,默认是 2113929216bit,原来是和 JVM 堆大小有关,谢谢你噢
|