ThreadMXBean.findDeadlockedThreads returns IDs of platform threads in a detected lock cycle, or null when none are found. It is a diagnostic snapshot, not a recovery mechanism.
Java ThreadMXBean deadlocks: diagnose platform-thread cycles
Operational contract
This method retrieves the bean, asks for deadlocked IDs, and resolves each ID to a short ThreadInfo. A thread can disappear between those calls, so null ThreadInfo entries are ignored. Some JVMs may not support the requested synchronizer inspection; an UnsupportedOperationException must be reported instead of being translated into 'no deadlock'. The API does not detect cycles involving virtual threads, and a non-null result does not identify which business operation should be rolled back. Capture the broader thread state under an incident policy before terminating anything.
Failure case
A shipment service stops making progress while CPU is low. A probe finds a cycle between two platform threads holding separate locks. The IDs and names help narrow the incident; restarting a thread blindly can leave data inconsistent. If the probe returns null, the service may still be stuck on I/O, queue admission, or a virtual-thread wait.
Java code
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
public class PlatformDeadlockSnapshot {
public static List<String> threadNames() {
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
long[] ids = threads.findDeadlockedThreads();
if (ids == null) return List.of();
List<String> names = new ArrayList<>();
for (long id : ids) {
ThreadInfo observed = threads.getThreadInfo(id, 47);
if (observed != null) names.add(observed.getThreadName());
}
return names;
}
}Performance and ownership cost
A deadlock scan can be expensive relative to an ordinary counter read because it inspects thread and lock state. The returned list uses O(D) memory for D reported threads. Run it on a deliberate diagnostic path, not on every request.
Common Mistakes
- Do not translate unsupported inspection into an empty result.
- Do not assume virtual-thread cycles are covered.
- Do not treat a deadlock snapshot as permission to kill a thread or roll back work.
Connected lessons
- Java threads: visibility, atomicity, and shared counters
- Java concurrency reference: admission, visibility, atomicity and completion
- Java JFR incident evidence: outcome events and failure counts
- Java ThreadMXBean CPU time: check support and the disabled state
- Java MemoryMXBean: read used, committed, and an optional maximum
- Java ClassLoadingMXBean: separate live classes from lifetime totals
- Java file channels and JVM observations quiz
- Advanced Java
