PhantomReference的 Javadoc 8 状态:
幻影引用最常用于以比 Java 终结机制更灵活的方式调度事前清理操作。
因此,我尝试创建一个线程,该线程调用close()
符合垃圾收集条件的测试对象的方法。run()
尝试获取所有测试对象pre -mortem。
实际上检索到的测试对象都是null
. 预期的行为是检索测试对象并close
调用方法。
无论您创建了多少测试对象,都没有一个测试对象可以事前捕获(您必须增加超时并多次调用 GC)。
我究竟做错了什么?这是一个Java错误吗?
可运行的测试代码:
我试图创建一个Minimal, Complete, and Verifiable example,但它仍然很长。我java version "1.8.0_121"
在 Windows 7 64 位上使用 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