Determining When an Object Will Be Reclaimed - Java Java Virtual Machine

Java examples for Java Virtual Machine:Utility

Description

Determining When an Object Will Be Reclaimed

Demo Code

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

public class Main {
  public static void main(String[] argv) {
    ReferenceQueue rq = new ReferenceQueue();
    String object = "";
    PhantomReference pr = new PhantomReference(object, rq);

    // Wait until the object is about to be reclaimed.
    try {/*from   w ww  .ja va2s . c o  m*/
      while (true) {
        Reference r = rq.remove();
        if (r == pr) {
          r.clear();
        }
      }
    } catch (InterruptedException e) {
    }
  }
}

Related Tutorials