Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why thread.stop deprecated and timer.cancel is not?

Tags:

java

What is the difference between stopping a java Thread and stopping an instance of Timer ?

Why is timer.cancel thread safe or is it ?

like image 449
blue-sky Avatar asked Dec 04 '22 21:12

blue-sky


2 Answers

Cancelling a timer doesn't have any of the potentially destabilizing behaviour of aborting a thread. From the docs:

Does not interfere with a currently executing task (if it exists).

In other words, it's not going to try to stop a task which is already running, which could potentially end up with monitors not being released etc. It's just going to avoid running any more tasks.

like image 162
Jon Skeet Avatar answered Dec 21 '22 23:12

Jon Skeet


Timer.cancel only cancels timer tasks that have not yet been started. The Thread.stop method stops the thread (by throwing an Error) and may leave the system in an inconsistent state, since the thread is stopped in an unknown place, possibly while doing something.

like image 39
Mathias Schwarz Avatar answered Dec 21 '22 23:12

Mathias Schwarz