title: What is the safest/best way to stop a thread and run some clean-up code
body: <p>As part of my efforts to implement a voice recognition program in Java I have implemented the actual voice recognition code in a separate thread. The main thread handles the GUI interface and receives constant updates from the voice recognition thread when words are identified.</p>
  
  <p>When the user clicks the Quit button in the GUI on the main thread I want this thread to immediately run some clean-up code and terminate.</p>
  
  <p>I currently have the following:</p>
  
  <pre><code>public class VoiceRecognitionCore extends SwingWorker&lt;List&lt;String&gt;, String&gt;
  {
      //Variables and things here
  
      @Override
      public List&lt;String&gt; doInBackground() throws VoiceRecognitionException
      {
          //Code here
          while(continueVoiceRecog == true)
          {
               //More code
               Result result = recog.recognize();
               //More code
          }
      }
  }
  </code></pre>
  
  <p>Where I rely on the while loop to constantly check the status of continueVoiceRecog which will be set to false by the main thread when the user clicks "Quit".</p>
  
  <p>The current problem is that the code can sometimes permanently sit inside the recog.recognize() method so it'll never get back to the while check. It should be noted that this was always intended as a temporary solution.</p>
  
  <p>I'm thinking of extending doInBackground() to catch InterruptedException and will use a thread interrupt which will call a cleanup method to deallocate any resources being used.</p>
  
  <p>What is the safest/best approach for this scenario? If it is what I propose, are there any potential issues I should be aware of?</p>