We can use ThreadMXBean.findDeadlockedThreads() method to
detect deadlocks in Java program. This bean comes with JDK:
Sample code is as follows:
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] threadIds = bean.findDeadlockedThreads(); // It will return
null for no deadlock
if (threadIds != null) {
ThreadInfo[] infos = bean.getThreadInfo(threadIds);
for (ThreadInfo info : infos) {
StackTraceElement[] stack = info.getStackTrace();
// Log or store stack trace information.
}
}