views:

699

answers:

1

A backend webapp is deployed on a Tomcat 6 servlet container. In the webapp, several monitoring threads are started. The problem is with shutdown.

  • How do I know that the webapp is requested to shutdown?
  • How should I handle this in my threads?

Currently my thread is implemented as below. When the servlet is instructed to shutdown (shutdown.sh) it does complete a clean shutdown and does not hang because of this thread -- Why?

class Updater extends Thread {
  volatile boolean interrupted = false;

  @Override
  public void run() {
    Integer lastUpdateLogId = CommonBeanFactory.getXXX()
                              .getLastUpdateLogRecordKey(MLConstants.SMART_DB_NAME);

    List<UpdateLog> updateLogRecords;
    while (!interrupted) {
      boolean isConfigurationUpdateRequested = false;

      try {
        TimeUnit.SECONDS.sleep(5);
      } catch (InterruptedException e) {
        setInterrupted(true);
      }

      updateLogRecords = CommonBeanFactory.getXXX()
                         .getLastFactsUpdateLogRecords(MLConstants.XXXX, lastUpdateLogId);

      for(UpdateLog updateLog : updateLogRecords) {
        if (updateLog.getTable_name().equals(MLConstants.CONFIG_RELOAD)) {
          isConfigurationUpdateRequested = true;
        }

        lastUpdateLogId = updateLog.getObjectKey();
      }

      if (isConfigurationUpdateRequested) {
        Configuration.getInstance().loadConfiguration();
      }
    }
  }

  public boolean getInterrupted() {
    return interrupted;
  }

  public void setInterrupted(boolean interrupted) {
    this.interrupted = interrupted;
  }
}
+1  A: 

Servlets receive a lifecycle event when instructed to shut down. You can use this event to stop your monitoring Thread. That is, when a servlet is started, its init() method is called. When it is stopped, its destroy() method is called.

Override the destroy() method in your servlet and stop the thread there.

When you call shutdown.sh the whole JVM is shut down. Because the JVM stops, all threads (no matter what their state) are forcibly stopped if still running. It's the logical equivalent of calling System.exit(0);

Eddie