Counter with Synchronization

Intermediate Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

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

  1. Explain lost increments without protection.
  2. Apply the same visibility rules to read and write methods.
  3. 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.

University approvals: 0
Tasks
Question 1

Implement increment() and get() synchronized.

Hint

synchronized appears in the method signature before the return type. Instance fields are directly accessible in both methods.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Question 2

Why is volatile int count not sufficient for count++?

Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Intermediate
  • Completed: 0 users
Creator
Best
Best
BestBuddy