Denis Kulagin
Denis Kulagin

Reputation: 8947

Java: How to forcefully kill unneeded thread?

I am using some 3rd party code, which may hang indefinitely in some cases. This leads to hanging threads which keep holding the resources and clogging a thread pool.

Eventually thread pool becomes full of useless threads and system effectively fails.

In Java one can't forcefully kill the thread (kill -9). But how then to manage such edge cases?

Upvotes: 0

Views: 254

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533870

Obviously fixing the bug would be better, however alternative include

  • only run the 3rd party code/library in a sub-process. Just killing the thread is unlikely to be enough.
  • you could hack the 3rd party code to check for interrupts in the sections you find run for too long. You can take a stack trace to run out where this is.
  • Use Thread.stop() though this has been disabled in Java 8.
  • when you detect there is a hung thread, increase the size of the thread pool by one. This will give you the correct number of active threads.

Upvotes: 2

Related Questions