Programmatic deadlock detection in java

You can do this programmatically using the ThreadMXBean that ships with the JDK: ThreadMXBean bean = ManagementFactory.getThreadMXBean(); long[] threadIds = bean.findDeadlockedThreads(); // Returns null if no threads are deadlocked. if (threadIds != null) { ThreadInfo[] infos = bean.getThreadInfo(threadIds); for (ThreadInfo info : infos) { StackTraceElement[] stack = info.getStackTrace(); // Log or store stack trace information. … Read more

Check to see if a pthread mutex is locked or unlocked (After a thread has locked itself)

You can use pthread_mutex_trylock. If that succeeds, the mutex was unclaimed and you now own it (so you should release it and return “unheld”, in your case). Otherwise, someone is holding it. I have to stress though that “check to see if a mutex is unclaimed” is a very bad idea. There are inherent race … Read more

Deadlock detection in Java

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[] … Read more

Would you explain lock ordering?

In the simple case given, unlocking in the reverse order is not necessary to avoid a deadlock. However, as the code gets more complicated, unlocking in the reverse order helps you maintain proper lock ordering. Consider: A.lock(); B.lock(); Foo(); A.unlock(); Bar(); B.unlock(); If Bar() attempts to reacquire A, you’ve effectively broken your lock ordering. You’re … Read more