title: How to ensure finalize() is always called (Thinking in Java exercise)
body: <p>I'm slowly working through Bruce Eckel's <em>Thinking in Java 4th edition</em>, and the following problem has me stumped:</p>
  
  <blockquote>
    <p>Create a class with a finalize( ) method that prints a message. In main( ), create an object of your class. Modify the previous exercise so that your finalize( ) will always be called.</p>
  </blockquote>
  
  <p>This is what I have coded:</p>
  
  <pre><code>public class Horse {
      boolean inStable;
      Horse(boolean in){
          inStable = in;
      }   
      public void finalize(){
          if (!inStable) System.out.print("Error: A horse is out of its stable!");
      }
  }
  public class MainWindow {
      public static void main(String[] args) {
          Horse h = new Horse(false);
          h = new Horse(true);
          System.gc();
      }
  }
  </code></pre>
  
  <p>It creates a new <code>Horse</code> object with the boolean <code>inStable</code> set to <code>false</code>. Now, in the <code>finalize()</code> method, it checks to see if <code>inStable</code> is <code>false</code>. If it is, it prints a message. </p>
  
  <p>Unfortunately, no message is printed. Since the condition evaluates to <code>true</code>, my guess is that <code>finalize()</code> is not being called in the first place. I have run the program numerous times, and have seen the error message print only a couple of times. I was under the impression that when <code>System.gc()</code> is called, the garbage collector will collect any objects that aren't referenced.</p>
  
  <p>Googling a correct answer gave me <a href="http://greggordon.org/java/tij4/initialization/BankTest.java" rel="noreferrer">this link</a>, which gives much more detailed, complicated code. It uses methods I haven't seen before, such as <code>System.runFinalization()</code>, <code>Runtime.getRuntime()</code>, and <code>System.runFinalizersOnExit()</code>.</p>
  
  <p>Is anybody able to give me a better understanding of how <code>finalize()</code> works and how to force it to run, or walk me through what is being done in the solution code?</p>