使用 PhantomReference 的例子
Example of using PhantomReference
据我所知,当引用指向的对象被删除时,引用会落入 QueueReference
。
这里是我要演示的示例,但它不起作用。 if
里面的代码从来没有被执行过。这是什么意思。我用错了吗?或者GarbageCollector
在执行过程中没有起作用?
public static void main (String[] arg) throws InterruptedException {
List<String> names = Arrays.asList("Adam", "Eva");
ReferenceQueue<List<String>> q = new ReferenceQueue<>();
PhantomReference<List<String>> phantom = new PhantomReference<>(names, q);
names = null;
while(true){
PhantomReference ref2 = (PhantomReference)q.poll();
if(ref2 != null)
System.out.println(ref2.enqueue());
Thread.sleep(1000);
}
}
PhanomReference 会在 GC 运行时被清除,尝试 System.gc() :
while (true) {
System.gc();
据我所知,当引用指向的对象被删除时,引用会落入 QueueReference
。
这里是我要演示的示例,但它不起作用。 if
里面的代码从来没有被执行过。这是什么意思。我用错了吗?或者GarbageCollector
在执行过程中没有起作用?
public static void main (String[] arg) throws InterruptedException {
List<String> names = Arrays.asList("Adam", "Eva");
ReferenceQueue<List<String>> q = new ReferenceQueue<>();
PhantomReference<List<String>> phantom = new PhantomReference<>(names, q);
names = null;
while(true){
PhantomReference ref2 = (PhantomReference)q.poll();
if(ref2 != null)
System.out.println(ref2.enqueue());
Thread.sleep(1000);
}
}
PhanomReference 会在 GC 运行时被清除,尝试 System.gc() :
while (true) {
System.gc();