It is very important that any threads that you startup in a webapp be stopped when the webapp shuts down. Failure to do so may prevent the server JVM from terminating (since a JVM cannot halt until all threads are stopped), and at a minimum, the server will probably whine at you.

So you are doing the right thing and the servlet's destroy() method is the place to do it, if you start the thread in init(). However, these days, the recommended place for starting and stopping application threads is in a ServletContextListener.

Ideally, your thread will have a notification mechanism, which can be something as simple as a member variable named "stopMe" that can be set to tell the thread to collect all its toys, put them away, and exit. If the thread can't be shut down that way, then the thread cancel() method may be used to brute-force terminate it.

Though just a convention,a thread's run method should be written in a way that it is capable of completing the execution on it's own i.e it should have the provision to terminate on its own rather than force stopping.But that might not be possible every time.

William Brogden

Author and all-around good cowpoke
Rancher

Posts: 13078

6

posted 1 year ago

Now I am not up to speed with the latest Java SDK - when did Thread get a cancel() method? I see there is one in Timer.

Java 1.2 had lots of Thread methods that were determined to be dangerous because they could leave the JVM in an undefined state. See the JavaDocs for discussion of why destroy, suspend, stop, and resume are deprecated.

Bill

Campbell Ritchie

Marshal

Posts: 54866

155

posted 1 year ago

William Brogden wrote:Now I am not up to speed with the latest Java SDK - when did Thread get a cancel() method? I see there is one in Timer. . . .

What cancel method? I couldn't find one. That Timer method might stop its thread by making a flag turn false.