use of synchronized keyword can cause thread suspension and can be costly, hence atomics are used
Internally implemented by low level atomic algorithms like CAS (Compare and Swap)
example classes:
AtomicInteger
AtomicLong
AtomicBoolean
AtomicReference
methods supported
get(), incrementAndGet(), set() etc.
The following code is problematic because count++ is combination of multiple steps and concurrent execution can cause inconsistencies. The steps are:
read count
add count with 1
update count
// problematic codepublic class Counter { int counter; public void increment() { counter++; }}
Solution 1: Use synchronized keyword
Slow, suspending thread issue
public class SafeCounterWithLock { private int counter; public synchronized void increment() { counter++; }}
Solution 2: Use AtomicInteger
public class SafeCounterWithoutLock { private final AtomicInteger counter = new AtomicInteger(0); public int getValue() { return counter.get(); } public void increment() { counter.incrementAndGet(); }}
These actions are atomic:
Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double)
Reads and writes are atomic for all variables declared volatile (includinglong and double variables)