advancedAdvanced & Design

How do you detect a deadlock in a running JVM?

There are three practical ways to detect a deadlock. The command-line tool jstack <PID> prints a full stack trace for every thread in the target JVM, and if a deadlock exists it explicitly prints a "Found one Java-level deadlock:" section that lists which threads hold which locks and what each of them is currently waiting for. Graphical tools like VisualVM or JConsole offer a thread dump viewer with a built-in deadlock detection button that presents the same information visually. You can also detect deadlocks programmatically through JMX by calling ManagementFactory.getThreadMXBean().findDeadlockedThreads(), which returns the IDs of any deadlocked threads or null if there are none -- running this check periodically as a scheduled task in production lets you alert an on-call engineer before users even notice the problem.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What are the different ways to design a thread-safe Singleton in Java?← Back to all Java Concurrency & Multithreading questions