Use a flag, which will indicate the thread should be terminated or not.
When you wish to stop the thread, you just set this flag and call join() method and wait for it to finish.
Make sure that the thread is thread safe and use the getter and setter method to synchronize the variable used as flag.
public class IndexProcessor implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean running = true;
public void terminate() { running = false; }@Override public void run() { while (running) { try {LOGGER.debug("Sleeping...");Thread.sleep((long) 15000);LOGGER.debug("Processing"); } catch (InterruptedException e) {LOGGER.error("Exception", e);running = false; } } } }
And in SearchEngineContextListener:
public class SearchEngineContextListener implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);
private Thread thread = null;
private IndexProcessor runnable = null;
@Override
public void contextInitialized(ServletContextEvent event) {
runnable = new IndexProcessor();
thread = new Thread(runnable);
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) {
runnable.terminate();
thread.join();
LOGGER.debug("Thread successfully stopped."); } } }