title: How to process SIGTERM signal gracefully in Java?
body: <p>Let's assume we have such a trivial daemon written in java:</p>
  
  <pre><code>public class Hellow {
      /**
       * @param args the command line arguments
       */
      public static void main(String[] args) {
          while(true) {
              // 1. do
              // 2. some
              // 3. important
              // 4. job
              // 5. sleep
          }
  
      }
  }
  </code></pre>
  
  <p>and we daemonize it using <code>start-stop-daemon</code> which by default sends <code>SIGTERM</code> (TERM) signal on <code>--stop</code></p>
  
  <p>Let's suppose the current step performed is #2. And at this very moment we're sending TERM signal.</p>
  
  <p>What happens is that the execution terminates immediately.</p>
  
  <p>I've found that I can handle the signal event using <code>addShutdownHook()</code> but the thing is that it still interrupts the current execution and passes the control to handler:</p>
  
  <pre><code>public class Hellow {
      private static boolean shutdownFlag = false;
      /**
       * @param args the command line arguments
       */
      public static void main(String[] args) {
          // TODO code application logic here
          registerShutdownHook();
  
          try {
              doProcessing();
          } catch (InterruptedException ex) {
              System.out.println(ex);
          }
      }
  
      static private void doProcessing() throws InterruptedException {
          int i = 0;
          while(shutdownFlag == false) {
              i++;
              System.out.println("i:" + i);
              if(i == 5) {
                  System.out.println("i is 5");
                  System.exit(1); // for testing
              }
  
              System.out.println("Hello"); // It doesn't print after System.exit(1);
  
              Thread.sleep(1000);
          }
      }
  
      static public void setShutdownProcess() {
          shutdownFlag = true;
      }
  
      private static void registerShutdownHook() {
          Runtime.getRuntime().addShutdownHook(new Thread() {
              public void run() {
                  System.out.println("Tralala");
                  Hellow.setShutdownProcess();
              }
          });
      }
  }
  </code></pre>
  
  <p>So, my question is - is it possible to not interrupt the current execution but handle the <code>TERM</code> signal in a separated thread (?) so that I would able to set <code>shutdown_flag = True</code> so that loop in <code>main</code> would had a chance to stop gracefully?</p>