title: Stop a Background Thread Gracefully
body: <p>I was task with implementing a background thread to do backend async processing with the twist being were certain cases where the job needed to be externally stopped.</p>
  
  <p>I implemented it by wrapping everything within the Runnable in a try catch block and catch the InterruptionException, if caught the thread will simply return and exit.</p>
  
  <pre><code>Runnable task = () -&gt; {
      try {
          while (true) {
              // do stuff 
  
              // sleep for interval
              Thread.sleep(this.checkInterval);
          }
      } catch (InterruptedException ex) {
              // cleanup and exit
              return; // exit thread
      } catch (Exception ex) {
              // cleanup and exit
              return; // exit thread
      }
  };
  </code></pre>
  
  <p>I'm using the ExecutorService SingleThreadExecutor and submitting the job like the following.</p>
  
  <pre><code>this.job = executorService.submit(task);
  </code></pre>
  
  <p>Then I am stopping the thread using </p>
  
  <pre><code>boolean canceled = this.job.cancel(true);
  </code></pre>
  
  <p>It seems to work fine since the cancel causes an InterruptionException if the thread is running. </p>
  
  <p>Is this code safe, meaning when cancel is called its always guaranteed to kill the thread?</p>