我想在其他线程不再引用时正确关闭Closeable对象.
我写了一些小测试,但是在对象入队后get方法返回null,即poll方法返回没有指示对象的正确Object.
public static void main(String[] args)
{
ReferenceQueue<Closeable> reaped = new ReferenceQueue<Closeable>();
Closeable s = <SOME CLOSEABLE IMPL>;
WeakReference<Closeable> ws = new WeakReference<Closeable>(s, reaped);
s = null;
System.gc();
Closeable ro = (Closeable)reaped.poll().get();
ro.close();
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.任何帮助将不胜感激.
我正在尝试实现一种机制,当持有它们的对象死亡时删除缓存的文件,并决定使用PhantomReferences来获取有关对象的垃圾收集的通知.问题是我一直在经历着奇怪的行为ReferenceQueue.当我在代码中更改某些内容时,它突然不再获取对象.所以我试着让这个例子进行测试,并遇到了同样的问题:
public class DeathNotificationObject {
private static ReferenceQueue<DeathNotificationObject>
refQueue = new ReferenceQueue<DeathNotificationObject>();
static {
Thread deathThread = new Thread("Death notification") {
@Override
public void run() {
try {
while (true) {
refQueue.remove();
System.out.println("I'm dying!");
}
} catch (Throwable t) {
t.printStackTrace();
}
}
};
deathThread.setDaemon(true);
deathThread.start();
}
public DeathNotificationObject() {
System.out.println("I'm born.");
new PhantomReference<DeathNotificationObject>(this, refQueue);
}
public static void main(String[] args) {
for (int i = 0 ; i < 10 ; i++) {
new DeathNotificationObject(); …Run Code Online (Sandbox Code Playgroud)