Create Phantom Reference in Java

Description

The following code shows how to create Phantom Reference.

A phantom reference is used to determine when an object is just about to be reclaimed.

Example


/*  w  w  w. j  a  v a  2s. c o m*/
  



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

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

    while (true) {
      Reference r = rq.remove();
      if (r == pr) {
        // about to be reclaimed.
        r.clear();
      }
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Development »




Java Algorithms
Java Clipboard
Java Compiler
Java Desktop
Java Virtual Machine
Java Math
OS
Random
Java Robot
Java RuntimeMXBean
Java Timer
Java UUID
Java Internationalization