title: Watching the garbage collector bin an object
body: <p>I am trying to see when the garbage collector "garbage collects" an object. According to the documentation, the finalize() method is called once when the garbage collector "deletes" an object. </p>
  
  <p>I tried to override the finalise() to see if i can see at what point it is called after i nullify the object but i seem to be waiting indefinately. Should this work?</p>
  
  <pre><code>class Dog{
      ZiggyTest2 z;
      public Dog(ZiggyTest2 z){
          this.z = z;
      }
  
      protected void finalize() throws Throwable {
          try {
              synchronized(z){
                  System.out.println("Garbage collected");
                  z.notify();
              }
          } finally {
              super.finalize();
          }
      }
  }
  </code></pre>
  
  <p>And the main class:</p>
  
  <pre><code>class ZiggyTest2{
  
      public static void main(String[] args){
  
      ZiggyTest2 z = new ZiggyTest2();        
      Dog dog = new Dog(z);   
  
          synchronized(z){
              try{
                  dog = null;
                  z.wait();
              }catch(InterruptedException ie){
                  System.out.println("Interrupted");
              }           
          }
      }   
  }
  </code></pre>
  
  <p>What i want to do is to see the finalise() method get called after i nullify the Dog object. This is why i put the notify() statement inside the finalize() method. It is not working in that it just keeps waiting.. </p>
  
  <h2>Edit</h2>
  
  <p>Thanks guys. I got it to work after i modified ZiggyTest2 to add System.gc();</p>
  
  <pre><code>class ZiggyTest2{
  
      public static void main(String[] args){
  
      ZiggyTest2 z = new ZiggyTest2();        
      Dog dog = new Dog(z);   
  
          synchronized(z){
              try{
                  dog = null;
                  System.gc();
                  z.wait();
              }catch(InterruptedException ie){
                  System.out.println("Interrupted");
              }           
          }
      }   
  }
  </code></pre>
  
  <p>output:</p>
  
  <pre><code>C:\&gt;java ZiggyTest2
  Garbage collected
  </code></pre>