PhantomReference

The PhantomReference class describes a Reference object whose referent is phantom reachable.

The following code shows how to use PhantomReference to detect the finalization of a large object.

 
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

class LargeObject {
  private byte[] data = new byte[1024 * 1024 * 50]; // 50 megabytes
  private byte[] data2 = new byte[1024 * 1024 * 50]; // 50 megabytes
  
}

public class Main {
  public static void main(String[] args) {
    ReferenceQueue<LargeObject> rq = new ReferenceQueue<LargeObject>();
    PhantomReference<LargeObject> pr = new PhantomReference<LargeObject>(new LargeObject(), rq);

    while (rq.poll() == null) {
      System.out.println("waiting for large object to be finalized");
      byte[] b  = new byte[1024 * 1024 * 50]; // 50 megabytes
    }
    System.out.println("large object finalized");
    System.out.println("pr.get() returns " + pr.get());
  }
}
  
Home 
  Java Book 
    Language Basics  

Reference:
  1. Reference
  2. SoftReference
  3. WeakReference
  4. PhantomReference