title: interrupt all threads in Java in shutdown hook
body: <p>I have a simple java program that creates a series of temporary files stored in a local tmp directory.  I have added a simple shutdown hook that walks through all files and deletes them, then deletes the tmp directory, before exiting the program.  here is the code:</p>
  
  <pre><code>Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
      @Override
      public void run() {
          File tmpDir = new File("tmp/");
          for (File f : tmpDir.listFiles()) {
              f.delete();
          }
          tmpDir.delete();
      }
  }));
  </code></pre>
  
  <p>My problem is that the thread that creates these files may not have terminated upon launch of the shutdown hook, and therefore, there may be a file created after <code>listFiles()</code> is called.  this causes the tmp dir not to get deleted.  I have come up with 2 hacks around this:</p>
  
  <p>Hack # 1:</p>
  
  <pre><code>Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
      @Override
      public void run() {
          File tmpDir = new File("tmp/");
          while (!tmp.delete()){
                  for (File f : tmpDir.listFiles()) {
                  f.delete();
              }
          }
      }
  }));
  </code></pre>
  
  <p>Hack # 2:</p>
  
  <pre><code>Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
      @Override
      public void run() {
          try{
              Thread.sleep(1000);
          } catch(InterruptedException e){
              e.printStackTrace();
          }
          File tmpDir = new File("tmp/");
          for (File f : tmpDir.listFiles()) {
              f.delete();
          }
              tmpDir.delete();
          }
  }));
  </code></pre>
  
  <p>Neither is a particularly good solution.  What would be ideal is to have the shutdown hook wait until all threads have terminated before continuing.  Does anyone know if this can be done?</p>