Testing concurrent code question 164 of 180 senior
How do you test that something is not possible, such as a deadlock?
- Run it and see if it hangs
- Correct: Bound every wait so a hang fails, and report
ThreadMXBean.findDeadlockedThreads - Use
assertDoesNotThrow - It cannot be tested
A hang is the worst test outcome, because the build sits there until a job timeout kills it with no
information. Make it a failure with evidence instead: assertTimeoutPreemptively, a bounded
future.get(5, SECONDS), or a latch await whose boolean you assert.
Then add the diagnosis to the failure path:
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
long[] deadlocked = threads.findDeadlockedThreads();
assertNull(deadlocked, () -> Arrays.toString(threads.getThreadInfo(deadlocked, true, true)));
That turns "the build hung" into a report naming both threads and both locks. As always, a passing run proves the deadlock did not occur this time, not that the ordering is correct.
Quiz yourself on Testing concurrent code Suggest a correction