Javadoc 8 的虚拟参考 http://docs.oracle.com/javase/8/docs/api/java/lang/ref/PhantomReference.html状态:
虚拟引用最常用于调度验尸前与 Java 终结机制相比,清理操作的方式更加灵活。
所以我尝试创建一个调用的线程close()
符合垃圾回收条件的测试对象的方法。这run()
尝试获取所有测试对象验尸前.
实际上检索到的测试对象都是null
。预期的行为是检索测试对象并且close
方法被调用。
无论您创建多少个测试对象,都没有一个测试对象可以被捕获验尸前(你必须增加超时并多次调用GC)。
我究竟做错了什么?这是 Java 错误吗?
可运行的测试代码:
我尝试创建一个最小、完整且可验证的示例,但还是很长。我用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