Java Concurrency Interview

Testing concurrent code question 164 of 180 senior

How do you test that something is not possible, such as a deadlock?

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.

testing deadlock

Quiz yourself on Testing concurrent code Suggest a correction