Practice ยท 1 of 3
The Thread-Safe Counter
Implement inside Solution:
- static class RacyCounter with void inc() (count++ on a plain
field) and long value().
- static class SafeCounter with the same API backed by an
AtomicLong.
- static long hammer(Object counter, int threads, int perThread):
starts threads threads, each calling inc() perThread times via
reflection (RacyCounter or SafeCounter), joins them, then returns
value() via reflection.
With hammer(c, 4, 1000): RacyCounter usually loses updates (< 4000);
SafeCounter must ALWAYS return exactly 4000. The safe test runs the
hammer five times to make flakiness visible.
Difficulty: intermediate
Press Submit to check your solution.
Back to lesson: Practice: Concurrency Lab