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.