Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill deadlocked threads in Java?

I'd like to kill threads that are stuck in deadlock state. First, we can detect thread ids in deadlock state using the findDeadlockedThreads() method of the ThreadMXBean class in java.lang.management.

Then, I'd like to kill the threads by thread ids, and thus I have two related questions:
(1) How to get the control of a thread by thread id?
(2) How to kill a blocked thread? I think that invokting interrupt() method will give an exception to the thread and will kill the thread.

like image 611
Sangmin Avatar asked Dec 04 '09 22:12

Sangmin


2 Answers

The java.util.concurrent.Lock.lockInterruptibly() method is interruptable, the far more common synchronized locking is not. As mentioned in the documentation, the ability to enumerate deadlocked threads is intended as a debugging aid and not as a means to recover in a production environment.

In production it is probably safer to exit the whole process and restart.

like image 103
Mark Thornton Avatar answered Oct 27 '22 22:10

Mark Thornton


From the root threadgroup, you can have the Thread class enumerate all running threads. Then you can call Thread.stop on the one that matches your ID.

Having said that, this is highly dangerous due to the potential to leave objects in an inconsistent state. I don't believe that the interrupt method will cause a thread to be freed up that is stuck in waiting on a synchronization lock, so the (evil) stop methods

See also: "Java Thread Primitive Deprecation".

like image 3
jsight Avatar answered Oct 27 '22 21:10

jsight