gpt4 book ai didi

Java:PhantomReference、ReferenceQueue 和 finalize

转载 作者:搜寻专家 更新时间:2023-10-31 19:56:46 24 4
gpt4 key购买 nike

我有一个 PR,一个 PR 指向的对象 O,以及一个为 PR 设置的 RQ。我有一个不断轮询 RQ 的线程,当它在 RQ 中找到第一个引用时,该线程打印它找到它的时间,然后退出。

一切正常,但是当 O 完成时(无论多么微不足道),线程不再在 RQ 中找到引用并继续无限期地运行。

问题:为什么会这样?我正在使用 Sun JDK 1.6。

代码如下:

好案例

public class MyGCPhantom 
{
public static void main(String[] args) throws InterruptedException
{
GCPhantomObject p = new GCPhantomObject();
ReferenceQueue phantomQueue = new ReferenceQueue();
PhantomReference<GCPhantomObject> pr = new PhantomReference<GCPhantomObject>(p, phantomQueue);
new GCPhantomThread(phantomQueue, "Phantom").start();
p = null;

System.gc();
}
}

class GCPhantomObject
{
@Override
protected void finalize()
{
//System.out.println("GCPhantom finalized " + System.currentTimeMillis());
}
}

class GCPhantomThread extends Thread
{
private ReferenceQueue referenceQueue;
private String name;

GCPhantomThread(ReferenceQueue referenceQueue, String name)
{
this.referenceQueue = referenceQueue;
this.name = name;
}

@Override
public void run()
{
while(referenceQueue.poll() == null);
System.out.println(name + " found at " + System.currentTimeMillis());
}
}

坏情况

只需取消注释 GCPhantomObjectfinalize() 中的 SOP。

最佳答案

您的分析有些不对。在两者中,无论是好的情况还是坏的情况,您的对象都实现了finalize。在好的情况下,它会简单地实现它;在坏的情况下,非常重要。因此,明显的问题在于 finalize 的普通实现和非普通实现之间的区别。

我看不出为什么 JVM 会被规范强制将您的引用排入队列。您执行一次 GC 运行,然后继续等待某些事情发生。众所周知,任何非平凡的终结器都可能使对象复活,因此在它入队之前可能需要更多的 GC 周期。我建议添加更多 GC 调用。

另请注意,不建议您决定使用 poll 而不是 remove。您应该使用阻塞调用来防止忙轮询。

作为引用,这些是文档中的相关定义:

If the garbage collector determines at a certain point in time that the referent of a phantom reference is phantom reachable, then at that time or at some later time it will enqueue the reference.


An object is phantom reachable if it is neither strongly, softly, nor weakly reachable, it has been finalized, and some phantom reference refers to it.


A finalized object has had its finalizer automatically invoked.

关于Java:PhantomReference、ReferenceQueue 和 finalize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12933134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com