title: Sending shut down signal to another thread in Java
body: <p>I have an application that runs something repeatedly in a while loop in a separate thread until the user triggers a shut down signal. I can send the signal from main thread to the worker thread by setting a (volatile) boolean field in the worker thread, but is there any other way of shut down/interrupt a thread, e.g. by means of any utility from 'java.util.concurrent'?</p>
  
  <p>I have tried calling shutdown() or shutdownNow() method of the ExecutorService, but they fail to stop the worker thread. Also calling shutdown() and using <code>!Thread.currentThread().isInterrupted()</code> in the while condition as recommended <a href="https://stackoverflow.com/questions/4675956/how-a-threadpoolexecutor-with-busy-threads-is-killed">here</a> is failing to break the loop. The only other way I could find was to use a CountDownLatch, but here I would have to use <code>CountDownLatch.getCount() != 0</code> in the condition for while loop, but the javadoc documentation of this method says </p>
  
  <blockquote>
    <p>This method is typically used for debugging and testing purposes.</p>
  </blockquote>
  
  <p>which makes it a questionable approach IMO. Below is my sample code</p>
  
  <pre><code>class Worker implements Runnable {
      //private volatile boolean shutdown = false; --&gt; alternative to countdownlatch 
      @Override
      public void run() {
  
          while (countDownLatch.getCount() != 0) {
              //do some work    
          }
      }
  }
  
  public class App {
      public static void main(String[] args) {
  
      System.out.println("Press enter to stop");
  
      CountDownLatch countDownLatch = new CountDownLatch(1);
  
      ExecutorService es = Executors.newFixedThreadPool(1);
      es.execute(new Worker(countDownLatch));
  
      Scanner scanner = new Scanner(System.in);
      scanner.nextLine();
  
      System.out.println("Shut down signal received");
  
      countDownLatch.countDown();  //an alternative would be to set a boolean variable in worker
  
      es.shutdownNow();
  
  }
  }
  </code></pre>
  
  <p>Are there any other clean way of doing this?</p>