title: Stopping a thread in Spring
body: <p>In my Spring application, I start a thread like this.</p>
  
  <pre><code>import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.context.ApplicationListener;
  import org.springframework.context.event.ContextRefreshedEvent;
  import org.springframework.context.event.ContextStoppedEvent;
  import org.springframework.stereotype.Component;
  
  @Component
  public class RunBackgroundServices implements ApplicationListener&lt;ContextRefreshedEvent&gt; {
  
      private final BackgroundServices backgroundServices;
  
      private ExecutorService executor;
  
      @Autowired
      public RunBackgroundServices(BackgroundServices backgroundServices) {
          this.backgroundServices= backgroundServices;
      }
  
      @Override
      public void onApplicationEvent(ContextRefreshedEvent event) {
  
          executor = Executors.newSingleThreadExecutor();
          executor.submit(backgroundServices);
      }
  
      public void onApplicationEvent(ContextStoppedEvent event) {
          backgroundServices.close();
          executor.shutdownNow();
       }
  }
  </code></pre>
  
  <p>Here is the thread BackGroundServices.</p>
  
  <pre><code>public class BackgroundServices extends Thread {
  
      @Autowired
      HL7Listener hL7Listener;
  
      @Autowired
      HISListener hISListener;
  
      @Autowired
      PollHIS pollHIS;
  
      @Autowired
      PollPatientPortal pollPatientPortal;
  
      private static final Logger logger = LoggerFactory.getLogger(BackgroundServices.class);
  
      public void run() {
          logger.debug("BackgroundServices :: run");
          try {
              hL7Listener.start();
          } catch (InterruptedException e) {
              logger.error(e.getStackTrace().toString());
          }
  
          try { 
              hISListener.start();
          } catch (InterruptedException e) {
              logger.error(e.getStackTrace().toString());
          }
  
          while (true) {
              pollHIS.start();
              pollPatientPortal.start();
          }
      }
  
      public void close(){
          hL7Listener.stop();
          hISListener.stop();
      }
  }
  </code></pre>
  
  <p>But when I stop the server, the thread continues running in the background. I have no control over the executor, is there a way to stop the thread?</p>