1. AtomicBoolean: | Atomically updatable Boolean value. |
2. AtomicInteger: | Atomically updatable int value; inherits from the Number class. |
3. AtomicIntegerArray: | An int array in which elements can be updated atomically. |
4. AtomicLong: | Atomically updatable long value; inherits from Number class. |
5. AtomicLongArray: | A long array in which elements can be updated atomically. |
6. AtomicReference < V>: | An atomically updatable object reference of type V. |
7 AtomicReferenceArray < E> : | An atomically updatable array that can hold object references of type E (E refers to be base type of elements). |
java.util.concurrent.atomic
package defines multiple classes that support atomic operations of read-compare/modify-write on single variables. At the surface, these operations might seem similar to the operations with volatile variables. Though modifications to a volatile variable are guaranteed to be visible to other threads, volatile variables cannot define a sequence of operations (like read-compare/modify-write) as an atomic operation. Here is an example of class Book to show you how nonatomic operations with primitive variables can lead to thread interference:
class Book{ String title; int copiesSold = 0; Book(String title) { this.title = title; } public void newSale() { // line 1 ++copiesSold; } public void returnBook() { // line 2 --copiesSold; } }Lines 1 and 2 above: Nonatomic statements include loading of variable values from memory to registers, manipulating values, and loading them back to memory.
class Book{ String title; AtomicInteger copiesSold = new AtomicInteger(0); Book(String title) { this.title = title; } public void newSale() { copiesSold.incrementAndGet(); } public void returnBook() { copiesSold.decrementAndGet(); } }