gpt4 book ai didi

java - 等待特定对象的垃圾收集

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

我刚刚在 commons-io 库中挖掘并发现了这个:

Keeps track of files awaiting deletion, and deletes them whenan associated marker object is reclaimed by the garbage collector.

这可以在 FileCleaningTracker 的文档中找到对象。

现在我很好奇我自己怎么能做到这一点?我的代码如何检测对象何时被垃圾收集器回收?

最佳答案

根据 the source code , 它使用 PhantomReference类(class)。根据文档:

Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.

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.

In order to ensure that a reclaimable object remains so, the referent of a phantom reference may not be retrieved: The get method of a phantom reference always returns null.

Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable.

PhantomReference 构造函数接受两个参数:

referent - the object the new phantom reference will refer to

q - the queue with which the reference is to be registered, or null if registration is not required

q 参数是 ReferenceQueue 类的实例。 PhantomReference 将被添加到此 ReferenceQueue 中,当它的 referent 变为 phantom reachable 时。发生这种情况时,您可以使用 ReferenceQueuepoll()remove() 方法检索 PhantomReference > 类。

例如:

T objectToWatch = ...;
ReferenceQueue<T> referenceQueue = new ReferenceQueue<T>();
new PhantomReference<T>(objectToWatch, referenceQueue);

// Later on, probably in another thread...
Reference<? extends T> nextReference = referenceQueue.remove();
// Tidy up!

注意:PhantomReference 具有名为 SoftReference 的兄弟类和 WeakReference这也可能有用。这些之间的关系记录在 java.lang.ref package documentation 中。 .

关于java - 等待特定对象的垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1227557/

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