0
class A {

}

public class Test {
public static void main(String[] args) throws Exception {
    ReferenceQueue<A> queue = new ReferenceQueue<>();  
    WeakReference<A> ref = new WeakReference<>(new A(), queue);  
    System.out.println("ref.get() == null:" + (ref.get() == null));

    Object obj = null;  
    obj = queue.poll();  
    System.out.println("obj == null:" + (obj == null));

    System.gc();  

    System.out.println("ref.get() == null2:" + (ref.get() == null));
    obj = queue.poll();  
    System.out.println("obj == null2:" + (obj == null));

    System.out.println(obj instanceof A);
}

}

The result is :

ref.get() == null:false
obj == null:true
ref.get() == null2:true
obj == null2:false
false

My question is: what exactly the obj is after gc? I thought is the A object before, but the result show not. Is that the ref itselft have been put into the queue? If true, when will the ref be cleared or when will the queue be empty?

gesanri
  • 237
  • 1
  • 3
  • 10

0 Answers0