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

Program hangs if thread is created in static initializer block

You’re not just starting another thread – you’re joining on it. That new thread has to wait for StaticInitializer to be fully initialized before it can proceed, because it’s trying to set the state field… and initialization is already in progress, so it waits. However, it’s going to be waiting forever, because that initialization is … Read more

Diagnosing Deadlocks in SQL Server 2005

According to MSDN: http://msdn.microsoft.com/en-us/library/ms191242.aspx When either the READ COMMITTED SNAPSHOT or ALLOW SNAPSHOT ISOLATION database options are ON, logical copies (versions) are maintained for all data modifications performed in the database. Every time a row is modified by a specific transaction, the instance of the Database Engine stores a version of the previously committed image … 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