package com;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
public class Main {
static Weak weak;
static class Weak {
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("finalize() is called");
weak = this;//复活对象
System.out.println("after finalize ,object is alive again");
}
}
public static void main(String[] args) throws InterruptedException {
weak = new Weak();
ReferenceQueue queue = new ReferenceQueue<>();
WeakReference<Weak> weakReference = new WeakReference<Weak>(weak, queue);
// PhantomReference<Weak> weakReference = new PhantomReference<>(weak,queue);
if (weakReference.get() == null) {
System.out.println("before gc : reference is not available");
} else {
System.out.println("before gc : reference is available");
}
weak = null;
System.gc();//执行GC线程
Thread.sleep(3000);
if (weakReference.get() == null) {
System.out.println("after gc : reference is not available");
} else {
System.out.println("after gc : reference is available");
}
if (queue.poll() == null) {
System.out.println("after gc : reference is not in queue");
} else {
System.out.println("after gc : reference is in queue");
}
weak=null;
System.gc();//再次执行GC
Thread.sleep(3000);
if (queue.poll() == null) {
System.out.println("gc agaain : reference is not in queue");
} else {
System.out.println("gc agaain : reference is in queue");
}
}
}
output:
before gc : reference is available
finalize() is called
after finalize ,object is alive again
after gc : reference is not available
after gc : reference is in queue
gc agaain : reference is not in queue
和上面相同的代码,输出如下:
before gc : reference is not available
finalize() is called
after finalize ,object is alive again
after gc : reference is not available
after gc : reference is not in queue
gc again : reference is in queue