How do I stop a daemon thread gracefully when the server shuts down?

karthik Natarajan

[ I have writeen a servlet which performs a task repeatedly after every fifteen minutes. I have used the run method and sleep for the same purpose. This servlet once started wiil go on executing the run method indefinitely . Obviously since the servlet will not be reloaded again and again the thread will not be spawned again and again. But when we close the servlet runner the servlet will end abruptly. How do I ensure that the thread is terminated properly when the servlet runner is shutdown.]

Instead of performing a sleep, you can perform a timed wait. (i.e) Instead of Thread.sleep(900000) use wait(900000).

For a graceful exit, you can interrupt the thread when you close the application. Handle the interrupted exception provided in wait. Also you can use isInterrupted to check if the thread is interrupted.