THINK FIRST·CODE LATER

← All labs

Linux in practice: catch a real Java deadlock

Problem

Create, observe and fix a real deadlock on your own machine (Linux, macOS or Windows with a JDK).

  1. Write Deadlock.java with two lock objects inventory and order and two threads: thread A locks inventory, sleeps 100 ms, then locks order; thread B locks order, sleeps 100 ms, then locks inventory. Each prints a message when it holds both locks. Run it and describe what you observe (output, CPU usage in top/Task Manager).
  2. While it hangs, find its process ID (jps -l) and run jstack <pid>. Copy the relevant part of the output and explain every line of the "Found one Java-level deadlock" section. Map it onto the four necessary conditions.
  3. Fix the program in two ways: (a) lock ordering; (b) ReentrantLock.tryLock(timeout) with release-and-retry. Run each fix 20 times and report whether it ever hangs.
  4. Add automatic detection: a watchdog thread that calls ManagementFactory.getThreadMXBean().findDeadlockedThreads() every second and prints the names of deadlocked threads. What should a production service do when this detects a deadlock?
  5. Reflection: why is the deadlock not visible as high CPU usage, and why did the 100 ms sleep make the deadlock appear every time? What happens if you remove it?

Work it out on paper, in a document or here, then compare with the model answer. Your answer stays in your browser — it is never sent to or stored on the server.