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?
If you are on Java 5 you can call the method
findMonitorDeadlockedThreads()
on the ThreadMXBean which you can get through a call ofjava.lang.management.ManagementFactory.getThreadMXBean()
. This will find deadlocks caused by object monitors only. On Java 6 there'sfindDeadlockedThreads()
which will also find deadlocks caused by "ownable synchronizers (for exampleReentrandLock
andReentrantReadWriteLock
).Be aware that it will probably be expensive to call these methods, so they should be used for troubleshooting purposes only.
you have to modify the code a little bit in the Deadlock Class
Also the above code will not always cause a dead lock, only some times it may happen.
Note that there is a type of deadlock using the concurrent package that is very hard to debug. That is where you have a ReentrantReadWriteLock and one thread grabs the read lock and then (say) tries to enter a monitor held by some other thread that is also waiting to grab the write lock. What makes it especially hard to debug is that there is no record of who has entered a read lock. It is simply a count. The thread might even have thrown an exception and died leaving the read count non-zero.
Here is a sample deadlock that the findDeadlockedThreads method mentioned earlier won't get: