import java.lang.ref.*;
import java.util.*;

public class JarJarToy {
    static int next = 0;

    int i;

    public JarJarToy () {
	i = (next++);
	new JarJarToyCleanupInfo (this);
    }

    public static void main (String args[]) {
	JarJarToy jj;
	while (true) {
	    jj = new JarJarToy ();
	}
    }
}

class JarJarToyCleanupInfo extends PhantomReference 
{
    static JarJarToyCleanupManager cm 
        = new JarJarToyCleanupManager ();
    static HashSet allocated = new HashSet ();
    
    int i;
    
    JarJarToyCleanupInfo (JarJarToy jj) {
	super (jj, cm);
	this.i = jj.i;
	allocated.add (this);
    }

    void doCleanup () {
	allocated.remove (this);
	System.out.println ("doCleanup() for " + i);
    }
}

class JarJarToyCleanupManager extends ReferenceQueue
{
    JarJarToyCleanupManager () 
    {
	new Thread () {
		public void run () {
		    JarJarToyCleanupInfo jjci;
		    try {
			while (true) {
			    jjci = (JarJarToyCleanupInfo) remove (0);
			    jjci.doCleanup ();
			    jjci.clear ();
			}
		    } catch (InterruptedException ie) {
			System.out.println ("Interrupted");
		    }
		}
	    }.start();
    }
}

