Demo: reproducing a race with a stress test
On This Lesson 3 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
prove a race exists before fixing it; prepares MID-004-LAB1.
Draft outline details
Step by step
- Write
StockCounterwithreserve(int)using check-then-act. - Stress test: 100 threads each reserve 1 unit from 1,000, started together with a
CountDownLatch; assert final stock is 900. - Run repeatedly; the test fails intermittently (stock above 900, or oversold).
- Planned mistake: add
volatileto the field and re-run; it still fails. Explain: visibility is not atomicity. - Fix with
synchronized; the test passes across many runs. - Note that a passing run is evidence only when the test failed before the fix.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.