/*********************************
* Class: ObjectWatcher
* @author Navneet Mathur
* Date:
* Class for detecting memory leaks. This class provides static methods to register
* and unregister objects as they are created and destroyed, it maintains a count of
* the number of each type of object that has been registered and has not been
* unregistered. On creation an object should register itself in its constructor,
* it should then unregister itself in its finalize() method.
*********************************/
package Util;
import java.util.*;

public class ObjectWatcher
{

    private static Hashtable TheObjects = new Hashtable(10);

    public static void Register( Object ThisRef )
    {
         String ClassName = ThisRef.getClass().getName();
         int count;

         // check if an object of this type has already been registered
         Object Obj = TheObjects.get( ClassName );
         if ( Obj != null )
         {
             Integer c = (Integer)Obj;
             count = c.intValue();
             count++;
             TheObjects.remove( ClassName );
         }
         else
         {
             count = 1;
         }
 
         TheObjects.put( ClassName, new Integer( count ));
    }

    public static void Unregister( Object ThisRef )
    {
         String ClassName = ThisRef.getClass().getName();
         int count;

         // check if an object of this type has already been registered
         Object Obj = TheObjects.get( ClassName );
         if ( Obj != null )
         {
             Integer c = (Integer)Obj;
             count = c.intValue();
             count--;
             TheObjects.remove( ClassName );
             TheObjects.put( ClassName, new Integer( count ));
         }
         else
         {
             DebugOut Debug = new DebugOut( true );
             Debug.println("Error: Unregister() for class '" + ClassName + "'" +
                                   ", class not previously registered" );
         }
    }

    public static String Dump()
    {
         String ClassName;
         Integer Count;
         StringBuffer res = new StringBuffer();
         DebugOut Debug = new DebugOut( true );

         for (Enumeration e = TheObjects.keys() ; e.hasMoreElements() ;)
          {
             ClassName = (String)e.nextElement();
             Count = (Integer)TheObjects.get( ClassName );
             res.append( ClassName + ":  " + Count.toString() + "\n" );
          }
         return res.toString();
     }
}

/*********************************
* Class: AnyClass
* @author Navneet Mathur
* Date:
* AnyClass that registers and unregisters
* itself with the ObjectWatcher class
*********************************/
import Util.ObjectWatcher

public class AnyClass
{
    AnyClass()
      {
        ObjectWatcher.Register(this);
        .
        .
        .
      }

    protected void finalize() throws Throwable
      {
        ObjectWatcher.Unregister(this);
      }
}