Create, observe and fix a real deadlock on your own machine (Linux, macOS or Windows with a JDK).
- Write
Deadlock.javawith two lock objectsinventoryandorderand two threads: thread A locksinventory, sleeps 100 ms, then locksorder; thread B locksorder, sleeps 100 ms, then locksinventory. Each prints a message when it holds both locks. Run it and describe what you observe (output, CPU usage intop/Task Manager). - While it hangs, find its process ID (
jps -l) and runjstack <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. - 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. - 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? - Reflection: why is the deadlock not visible as high CPU usage, and why did the 100 ms
sleepmake the deadlock appear every time? What happens if you remove it?