Command Palette

Search for a command to run...

Back to the lesson: Topic 14.5 — JVM Tools: jcmd, jstack, jmap and JFR
Core Java · Example 3 of 3

Detecting a deadlock from inside the JVM

The latch guarantees each thread holds its first lock before reaching for the second, so the deadlock happens every time. Lock ordering (Topic 13.9) is the cure.

The JDK ships tools that look inside a running JVM without restarting it: jcmd (the Swiss-army knife), jstack for thread dumps, jmap and heap dumps for memory, jstat for GC counters, and Java Flight Recorder (JFR) for low-overhead, always-on recording of what the JVM did. Knowing which one answers which question is most of production troubleshooting.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program that names three threads worker-1 to worker-3, starts them, joins them, and prints the names of all threads whose names start with worker- while they are alive (use a latch so they're all alive at once).

02

Use ThreadMXBean to print whether thread contention monitoring is supported and the number of threads that have been started by the JVM since start-up is at least 1.

03

Write a program that checks the JVM has at least one GarbageCollectorMXBean and that every collection count is at least zero, printing only collectors found: true (the real names and counts vary between runs and collectors).

Explain it without notes

01

A service is hung: requests time out but CPU is near zero. How do you investigate?

02

CPU is at 100% on a Java service. How do you find the code responsible?

03

What's the difference between a thread dump, a heap dump and a JFR recording?

04

Why should heap dumps be treated as sensitive data?

Detecting a deadlock from inside the JVM
Sign in to run this example in your browser.

Expected output

deadlocked threads: 2
transfer-1 is BLOCKED, waiting for a lock held by transfer-2
transfer-2 is BLOCKED, waiting for a lock held by transfer-1