Simple, concise Java examples that do useful things.

Thursday, November 23, 2006

Starting a worker thread in a Servlet Engine

Today's example shows how to create a background thread when your servlet context starts up, and how to end the thread's activities gracefully when the servlet context is destroyed. Take this example and add it as a "listener" in your web application, then using the Tomcat (or equivalent) manager start and stop the context and watch the stdout messages.


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Deamon implements ServletContextListener, Runnable {

private Thread t;

public void contextDestroyed(ServletContextEvent arg0) {
t.interrupt();}

public void contextInitialized(ServletContextEvent context) {
t = new Thread(this);
t.start();
System.out.println("deamon started");}

public void run() {
try {
while (true) {
System.out.println("deamon working...");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("deamon stopped");}
}
}