Declaring Methods  «Prev 


Atomic Variables in the java.util.concurrent.atomic package

Java provides atomic variables. Here is a list of some of the classes in this package and their short description:
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).


Atomic variables

The 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.
The code defined at lines 1 and 2 above is not atomic. Incrementing or decrementing primitive values includes multiple steps. When executed by multiple concurrent threads, newSale() and returnBook() can result in thread interference. To get around this, you can define these methods as synchronized methods, but it will block thread execution. Java defines multiple convenient classes in the java.util.concurrent.atomic package that define frequently used operations like read-modify-write as atomic operations. Let us use one of these classes, AtomicInteger, in class Book, and replace the type of its primitive int variable copiesSold:
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();
 }
}