AlgoMaster Logo
AlgoMasterDesign an Atomic Countereasy

Design an Atomic Counter

easy

Design a thread-safe integer counter whose read-modify-write operations are atomic.

Implement the AtomicCounter class:

  • AtomicCounter(initialValue) initializes the counter to initialValue.
  • incrementAndGet() atomically adds 1 and returns the new value.
  • addAndGet(delta) atomically adds delta and returns the new value.
  • get() atomically reads and returns the current value.

Every method must be linearizable. Each call must appear to take effect at one instant between its invocation and return. Consequently, concurrent updates cannot be lost, and two increments starting from the same state cannot both return the same new value.

The same counter may be accessed by many threads. The judge creates and coordinates those threads; your implementation should contain only the state and synchronization inside AtomicCounter.

Standard concurrency and thread APIs are preloaded, so you do not need import, include, or using statements.

Example 1:

Input:

Output:

Example 2:

Input:

Output:

Explanation: All 10000 increments are preserved even though the calls overlap.

Constraints

  • -1000000000 <= initialValue <= 1000000000
  • -1000000 <= delta <= 1000000
  • At most 50000 method calls are made per counter.
  • The counter's value always remains within the signed 32-bit integer range.
  • Any number of method calls may execute concurrently on the same instance.
  • Judge threads are not interrupted while executing a method.
Loading...

Input

counter = AtomicCounter(5)
counter.incrementAndGet()
counter.addAndGet(4)
counter.get()

Output

[6, 10, 10]

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.