Counter with Synchronization
Implement a thread-safe increment counter using synchronized.
Where used
Sample case for Shared Mutable State. In production, often AtomicInteger or Striped/LongAdder is used under high contention.
Depth
A synchronized counter protects reading and writing of the value using the same monitor. The increment operation must be treated as an atomic unit because it consists of multiple machine and language operations. Even a method like get requires synchronization or another visibility guarantee.
For a single counter, atomic classes often provide a more compact solution. However, once multiple fields together form an invariant, a single atomic value is not sufficient. Then the entire state transition must be modeled as a critical section.
Difficulty levels
- Explain lost increments without protection.
- Apply the same visibility rules to read and write methods.
- Weigh the differences between synchronized, AtomicInteger, and LongAdder.
Pitfalls
volatile does not make a composite increment atomic. LongAdder is suitable for high update rates but does not provide an atomic snapshot during concurrent modifications like a strictly coordinated counter.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Intermediate
- Completed: 0 users