检查一个对象是否被GC的方法

在Java中,可以使用PhantomReference来检查一个对象是否被GC,示例代码如下:

public void trackGC() throws InterruptedException {
Object o = new Object();
ReferenceQueue<Object> queue = new ReferenceQueue<>();
PhantomReference<Object> phantomReference = new PhantomReference<>(o, queue);
assertNull(queue.poll());
o = null;
System.gc();
Thread.sleep(1000);
assertNotNull(queue.poll());
}

这里有一点要注意, phantomReference不能在gc之前就赋值为null, 不然会收不到通知。
比如把

PhantomReference<Object> phantomReference = new PhantomReference<>(o, queue);

替换为:

new PhantomReference<>(o, queue);


PhantomReference<Object> phantomReference = new PhantomReference<>(o, queue);
phantomReference = null;

都会导致测试失败