Determining When an Object Is No Longer Used - Java Java Virtual Machine

Java examples for Java Virtual Machine:Utility

Description

Determining When an Object Is No Longer Used

Demo Code

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

public class Main {
  public static void main(String[] args) {
    ReferenceQueue rq = new ReferenceQueue();
    String object = "asdf";
    WeakReference wr = new WeakReference(object, rq);

    // Wait for all the references to the object.
    try {//from   ww  w. j a  v a 2  s .  co  m
      while (true) {
        Reference r = rq.remove();
        if (r == wr) {
          // Object is no longer referenced.
        }
      }
    } catch (InterruptedException e) {
    }
  }
}

Related Tutorials