Definition of AtomicInteger:
AtomicInteger is used primarily in multi-threaded environment when we need to process thread safe operations on an integer value without using synchronized keyword. Retrieving and assigning operations on primitive type int are already atomic but AtomicInteger provides many other operations which are not atomic. AtomicInteger is a wrapper class for int.
- AtomicInteger works on CAS(compare and swap) algorithm. CAS is a machine instruction.
- CAS algorithm compares the contents of a memory location to a given value and only if they are same, then it modifies the contents of that memory location to a given new value, this complete operation is done as a single atomic operation.
- CAS belongs to CPU so it is fast.
Since: JDK 1.5
Main methods of AtomicInteger:
- addAndGet(int n)
- getAndAdd(int n)
- compareAndSet(int expect, int update)
Beside atomicity, AtomicInteger can be used as a mutable version of Integer for instance in Maps as values.
AtomicInteger is fast and more readable than synchronization.