【发布时间】:2017-09-04 19:51:55
【问题描述】:
PhantomReference 的 Javadoc 8 状态:
幻影引用最常用于以比 Java 终结机制更灵活的方式调度 pre-mortem 清理操作。
所以我尝试创建一个线程,该线程调用符合垃圾回收条件的测试对象的close() 方法。 run() 尝试获取所有测试对象pre-mortem。
实际上检索到的测试对象都是null。预期的行为是检索测试对象并调用close方法。
无论您创建多少个测试对象,都没有一个可以被捕获的测试对象事前分析(您必须增加超时并多次调用 GC)。
我做错了什么?这是 Java 错误吗?
可运行的测试代码:
我尝试创建一个最小、完整且可验证的示例,但它仍然很长。我在 Windows 7 64 位上使用 java version "1.8.0_121" 32 位。
public class TestPhantomReference {
public static void main(String[] args) throws InterruptedException {
// Create AutoClose Thread and start it
AutoCloseThread thread = new AutoCloseThread();
thread.start();
// Add 10 Test Objects to the AutoClose Thread
// Test Objects are directly eligible for GC
for (int i = 0; i < 2; i++) {
thread.addObject(new Test());
}
// Sleep 1 Second, run GC, sleep 1 Second, interrupt AutoCLose Thread
Thread.sleep(1000);
System.out.println("System.gc()");
System.gc();
Thread.sleep(1000);
thread.interrupt();
}
public static class Test {
public void close() {
System.out.println("close()");
}
}
public static class AutoCloseThread extends Thread {
private ReferenceQueue<Test> mReferenceQueue = new ReferenceQueue<>();
private Stack<PhantomReference<Test>> mPhantomStack = new Stack<>();
public void addObject(Test pTest) {
// Create PhantomReference for Test Object with Reference Queue, add Reference to Stack
mPhantomStack.push(new PhantomReference<Test>(pTest, mReferenceQueue));
}
@Override
public void run() {
try {
while (true) {
// Get PhantomReference from ReferenceQueue and get the Test Object inside
Test testObj = mReferenceQueue.remove().get();
if (null != testObj) {
System.out.println("Test Obj call close()");
testObj.close();
} else {
System.out.println("Test Obj is null");
}
}
} catch (InterruptedException e) {
System.out.println("Thread Interrupted");
}
}
}
}
预期输出:
System.gc()
Test Obj call close()
close()
Test Obj call close()
close()
Thread Interrupted
实际输出:
System.gc()
Test Obj is null
Test Obj is null
Thread Interrupted
【问题讨论】:
-
Test testObj = mReferenceQueue.remove().get();将始终为 null 。将该代码块更改为mReferenceQueue.remove().close(),它将起作用。queue.remove()将正确阻止并始终返回一个对象。无需测试null。 -
你好@Pacerier。
mReferenceQueue.remove()将返回Reference<? extends Test>对象而不是Test对象,所以我不能调用mReferenceQueue.remove().close()。也许您可以提供更多详细信息。
标签: java garbage-collection finalizer finalize phantom-reference