title: How to properly stop the Thread in Java?
body: <p>I need a solution to properly stop the thread in Java.</p>
  
  <p>I have <code>IndexProcessor</code>class which implements the Runnable interface:</p>
  
  <pre><code>public class IndexProcessor implements Runnable {
  
      private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
  
      @Override
      public void run() {
          boolean run = true;
          while (run) {
              try {
                  LOGGER.debug("Sleeping...");
                  Thread.sleep((long) 15000);
  
                  LOGGER.debug("Processing");
              } catch (InterruptedException e) {
                  LOGGER.error("Exception", e);
                  run = false;
              }
          }
  
      }
  }
  </code></pre>
  
  <p>And I have <code>ServletContextListener</code> class which starts and stops the thread:</p>
  
  <pre><code>public class SearchEngineContextListener implements ServletContextListener {
  
      private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);
  
      private Thread thread = null;
  
      @Override
      public void contextInitialized(ServletContextEvent event) {
          thread = new Thread(new IndexProcessor());
          LOGGER.debug("Starting thread: " + thread);
          thread.start();
          LOGGER.debug("Background process successfully started.");
      }
  
      @Override
      public void contextDestroyed(ServletContextEvent event) {
          LOGGER.debug("Stopping thread: " + thread);
          if (thread != null) {
              thread.interrupt();
              LOGGER.debug("Thread successfully stopped.");
          }
      }
  }
  </code></pre>
  
  <p>But when I shutdown tomcat, I get the exception in my IndexProcessor class:</p>
  
  <pre><code>2012-06-09 17:04:50,671 [Thread-3] ERROR  IndexProcessor Exception
  java.lang.InterruptedException: sleep interrupted
      at java.lang.Thread.sleep(Native Method)
      at lt.ccl.searchengine.processor.IndexProcessor.run(IndexProcessor.java:22)
      at java.lang.Thread.run(Unknown Source)
  </code></pre>
  
  <p>I am using JDK 1.6. So the question is:</p>
  
  <p>How can I stop the thread and not throw any exceptions? </p>
  
  <p><strong>P.S.</strong> I do not want to use <code>.stop();</code> method because it is deprecated.</p>