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 running from the command-line and you suspect that you are deadlocked, try ctrl+break in windows (ctrl+\ in unix) to get a thread dump. See http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/gbmps.html
Java can detect deadlocks (although not at run-time, it can still diagnose and report it).
For example, when using a slightly modified version of 'Saurabh M. Chande' code bellow (changed it to Java and added some timing to guarantee a lock on each run). Once you run it and it deadlocks, if you type:
It will generate a stack dump, which will include the following information:
Not exactly what you asked, but when a deadlock does occur, you can do a "kill -3" on the process id and it dumps a thread dump to stdout. Also, the 1.6 jvm has some tools to do the same thing in a gui manner.
Java 5 introduced ThreadMXBean - an interface that provides various monitoring methods for threads. ... The difference is that findDeadlockedThreads can also detect deadlocks caused by owner locks (java.util.concurrent), while findMonitorDeadlockedThreads can only detect monitor locks (i.e. synchronized blocks)
Or you can detect it programatically, refer this https://dzone.com/articles/how-detect-java-deadlocks
Dr. Heinz Kabutz of JavaSpecialists has written an entertaining and informative newsletter issue on Java deadlocks and describes something called a ThreadMXBean in another newsletter issue. Between those, you should get a good idea of the issues and some pointers to doing your own instrumentation.
If you're debugging in eclipse, you can pause the application (select the app in the debug view and the little || button on the debug toolbar) and then it can report deadlocks.
See http://runnerwhocodes.blogspot.com/2007/10/deadlock-detection-with-eclipse.html for an example.