Why is thread.stop not recommended, but timer.cancel not?

What is the difference between stopping a Java thread and stopping a timer instance?

Why is timer.cancel thread safe or is it?

+4
source share
3 answers

Canceling a timer does not have any potentially destabilizing interruption behavior. From the docs :

Does not interfere with the current task (if it exists).

In other words, he is not going to stop a task that is already running, which could potentially lead to monitors not being released, etc. This will simply prevent the execution of any tasks.

+12
source

Timer.cancel cancels timer tasks that are not already running. The Thread.stop method stops the thread (by throwing an Error ) and can leave the system in an inconsistent state, since the thread is stopped in an unknown place, it is possible to do something.

+2
source

The Java Timer implementation uses a loop and flag to indicate whether its underlying Thread continue to process timer events. When you call cancel() , the newTasksMayBeScheduled flag is false, which clears any pending event events and causes the thread loop to stop (letting its run() method return). In other words, it does not use the unsafe Thread#stop() method.

+2
source

All Articles