Java Concurrency Interview

Testing concurrent code question 170 of 180 junior

What is the difference between assertTimeout and assertTimeoutPreemptively in JUnit 5?

assertTimeout runs the code on the test's own thread, lets it finish, and only then compares the time taken with the limit. That is fine for "this should be fast", and useless for "this might deadlock": a deadlocked call never returns, so the assertion never runs and the build hangs until CI kills it, with no message.

assertTimeoutPreemptively runs the code on a separate thread and stops waiting at the deadline, so the test fails on time and says why. Two costs come with the other thread:

The annotation form is @Timeout, with threadMode = SEPARATE_THREAD for the preemptive behaviour, and junit.jupiter.execution.timeout.default sets a limit for every test, which is a cheap safety net for a concurrency-heavy suite.

junit timeouts deadlock

Quiz yourself on Testing concurrent code Suggest a correction