Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use thread.stop () in Java if I really need it?

I need to use deprecated stop () because I need to run Runnable classes which were developed by other programmers and I can't use while (isRunning == true) inside method run.

The question is: Is it safety enough to use method stop ()? Theads don't work with any resources (like files, DB, or Internet connections). But I want to be sure that JVM wouln't be corrupted after I stop a dozen of threads with stop () method.

P.S.: yes, I can write some code to test it, but I hope somebody knows the answer)

like image 539
Roman Avatar asked Sep 02 '09 21:09

Roman


3 Answers

Sort of. There's nothing inherently "corrupting" about Thread.stop(). The problem is that it can leave objects in a damaged state, when the thread executing them suddenly stops. If the rest of your program has no visibility to those objects, then it's alright. On the other hand, if some of those objects are visible to the rest of the program, you might run into problems that are hard to diagnose.

like image 77
erickson Avatar answered Nov 14 '22 21:11

erickson


If you use Thread.stop you'll probably get away with, assuming you have few users. It is exceptionally hard to test for. It can cause an exception anywhere in executing code. You can't test all possible situations. On your machine in your set up you might never find a problem; come the next JRE update your program might start failing with a highly obscure intermittent bug.

An example problem case is if the thread is loading a class at the time. The class fails to load and will not be retried again. You program is broken.

like image 43
Tom Hawtin - tackline Avatar answered Nov 14 '22 22:11

Tom Hawtin - tackline


I addressed this in my question "Are thread stop and friends ever safe?", and in one of the answers, I tried to figure out preconditions that would make stop() safe to use. But this is still a "work in progress".

BTW: writing test code won't necessarily help. (Tests only prove the presence of bugs not the absence of bugs.) You would do better trying to reason about the problem, IMO. But it is not easy :-).

like image 29
Stephen C Avatar answered Nov 14 '22 21:11

Stephen C