Long time ago, I saved a sentence from a Java reference book: "Java has no mechanism to handle deadlock. it won't even know deadlock occurred." (Head First Java 2nd Edition, p.516)
So, what is about it? Is there a way to catch deadlock case in Java? I mean, is there a way that our code understands a deadlock case occurred?
The OS can detect the deadlocks with the help of Resource allocation graph. In single instanced resource types, if a cycle is being formed in the system then there will definitely be a deadlock. On the other hand, in multiple instanced resource type graph, detecting a cycle is not just enough.
JConsole is able to detect deadlocks in a running application.
We can avoid Deadlock situation in the following ways: Using Thread. join() Method: We can get a deadlock if two threads are waiting for each other to finish indefinitely using thread join. Then our thread has to wait for another thread to finish, it is always best to use Thread.
Deadlock in Java is a condition where two or more threads are blocked forever, waiting for each other. This usually happens when multiple threads need the same locks but obtain them in different orders. Multithreaded Programming in Java suffers from the deadlock situation because of the synchronized keyword.
Since JDK 1.5 there are very useful methods in the java.lang.management
package to find and inspect deadlocks that occurs. See the findMonitorDeadlockedThreads()
and findDeadlockedThreads()
method of the ThreadMXBean
class.
A possible way to use this is to have a separate watchdog thread (or periodic task) that does this.
Sample code:
ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); long[] ids = tmx.findDeadlockedThreads(); if (ids != null) { ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true); System.out.println("The following threads are deadlocked:"); for (ThreadInfo ti : infos) { System.out.println(ti); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With