Video in progress
How do you test concurrency bugs? Why isn't an ordinary unit test enough, and what does jcstress give you?
A unit test checks one interleaving, while the bug hides in an ordering that shows up one run in a million. jcstress is an OpenJDK tool: it runs a small piece of code in parallel millions of times, counts all the outcomes it sees, and flags the unexpected ones. On top of that come stress tests, static analysis and simple design.
📖 Answer
A concurrency bug often appears only when three conditions line up: the right interleaving, a JIT optimization, and certain hardware (for example, ARM). On a local machine in debug mode, none of them may be present.
A jcstress test looks like this:
@JCStressTest
@Outcome(id = "1, 1", expect = Expect.ACCEPTABLE, desc = "ikkalasi ham ko'rdi")
@Outcome(id = "0, 1", expect = Expect.ACCEPTABLE, desc = "faqat ikkinchisi")
@Outcome(id = "1, 0", expect = Expect.ACCEPTABLE, desc = "faqat birinchisi")
@Outcome(id = "0, 0", expect = Expect.ACCEPTABLE_INTERESTING, desc = "store buffering")
@State
public class StoreBufferingTest {
int x, y;
@Actor public void a(II_Result r) { x = 1; r.r1 = y; }
@Actor public void b(II_Result r) { y = 1; r.r2 = x; }
}
The "0, 0" outcome really does occur with plain fields, even on x86. If you add volatile, it goes away. This kind of check is for lock-free code, custom synchronizers and claims about safe publication.
Other layers:
- Stress test: start everything at the same moment with a
CountDownLatch, run many iterations, and check the result invariants (for example, the account balances always sum to zero). It isn't guaranteed to find the bug, but it catches regressions. - Deterministic test: inject time (
Clock) and the executor, and in the test run an exact order with a synchronous executor. - Static analysis: Error Prone (the
@GuardedBycheck), SpotBugs's MT detectors. - Lincheck (Kotlin/JVM) checks linearizability with model checking, and works for Java structures too.
- In prod: an alert when an invariant is violated, and automatic collection of thread dumps and JFR.
But the most effective "test" is design: reduce shared mutable state. Immutable objects, state with a single owner and ready-made concurrent structures shrink the very thing that has to be tested.
Sign up to mark studied questions and save your progress.