Wednesday 18 September 2019

How do find if your program has a deadlock?

deadlocked can be detected by programmatically or via some kind of external monitoring tool.

1) By taking thread dump using kill -3, using JConsole or VisualVM).

2) You can detect the deadlocked threads programmatically using ThreadMXBean class.Here is the code.

Example:

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class DeadLockDetectorDemo {
public static void main(String[] args) {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] threadIds = bean.findDeadlockedThreads(); // Returns null if no threads are deadlocked.

if (threadIds != null) {
    ThreadInfo[] infos = bean.getThreadInfo(threadIds);
System.out.println("Size::  "+infos.length);
    for (ThreadInfo info : infos) {
        StackTraceElement[] stack = info.getStackTrace();
        // Log or store stack trace information.
        System.out.println(stack);
    }
}else {
System.out.println("no dealock");
}
}

}

You can also run JMC(Java Machine control) in Java/bin/ and open threads tab and check the Deadlock Detection you can see yes.

No comments:

Post a Comment