0

Is there a way to stop, kill or destroy a kid thread by the main thread who started it?

Everyone suggest to use some variable to check inside the thead itself, for exit when variable change state. I can't do that, the thread is a very complex and big program and is not possible to foresee every conditions that could make it running in loop.

I need to force kill the thread from extern when time exceeded.

Thanks

  • 1
    Does this answer your question? [Is there a good way to forcefully stop a Java thread?](https://stackoverflow.com/questions/5241822/is-there-a-good-way-to-forcefully-stop-a-java-thread) – Amongalen Jun 25 '20 at 12:45
  • 1
    Nope, they suggest to use a flag variable and check it inside the thread itself, as i said in my question, i can't use this approach. – Roberto Jun 25 '20 at 12:46
  • Instead of playing around with threads yourself, Let `ExecutorService` do it. – Amit kumar Jun 25 '20 at 12:55
  • @Roberto They discussed all possible options in that post I linked. It was said in there that there isn't any other safe way to stop threads. – Amongalen Jun 25 '20 at 13:31

1 Answers1

2

No,

There is no safe way for one thread to forcibly kill another. There is no safe way for one thread to force another thread to do anything.

The problem is, threads communicate through shared variables. And, the author of any multi-threaded program must carefully "synchronize" the activities of the different threads, so that no thread can ever see the shared variables in some invalid state that was caused by the activity of another thread.

If you make it possible for a thread to be killed at any time, then there is no way you can ensure that the killed thread won't leave shared variables in an irreparably bad state.

If you can't work around the need to kill a "child," then you should re-write the code so that the child is a child process. Processes only share state in much more controlled ways, and it is much easier to write an application that can safely continue to execute after killing off a rogue child process.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57