title: Useful example of a shutdown hook in Java?
body: <p>I'm trying to make sure my Java application takes reasonable steps to be robust, and part of that involves shutting down gracefully. I am reading about <a href="http://www.ibm.com/developerworks/ibm/library/i-signalhandling/?open&amp;l=409,t=grj,p=jsh#9" rel="noreferrer">shutdown hooks</a> and I don't actually get how to make use of them in practice.</p>
  
  <p>Is there a practical example out there?</p>
  
  <p>Let's say I had a really simple application like this one below, which writes numbers to a file, 10 to a line, in batches of 100, and I want to make sure a given batch finishes if the program is interrupted. I get how to register a shutdown hook but I have no idea how to integrate that into my application. Any suggestions?</p>
  
  <pre><code>package com.example.test.concurrency;
  
  import java.io.File;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.PrintWriter;
  
  public class GracefulShutdownTest1 {
      final private int N;
      final private File f;
      public GracefulShutdownTest1(File f, int N) { this.f=f; this.N = N; }
  
      public void run()
      {
          PrintWriter pw = null;
          try {
              FileOutputStream fos = new FileOutputStream(this.f);
              pw = new PrintWriter(fos);
              for (int i = 0; i &lt; N; ++i)
                  writeBatch(pw, i);
          }
          catch (FileNotFoundException e) {
              e.printStackTrace();
          }
          finally
          {
              pw.close();
          }       
      }
  
      private void writeBatch(PrintWriter pw, int i) {
          for (int j = 0; j &lt; 100; ++j)
          {
              int k = i*100+j;
              pw.write(Integer.toString(k));
              if ((j+1)%10 == 0)
                  pw.write('\n');
              else
                  pw.write(' ');
          }
      }
  
      static public void main(String[] args)
      {
          if (args.length &lt; 2)
          {
              System.out.println("args = [file] [N] "
                      +"where file = output filename, N=batch count");
          }
          else
          {
              new GracefulShutdownTest1(
                      new File(args[0]), 
                      Integer.parseInt(args[1])
              ).run();
          }
      }
  }
  </code></pre>