Home | | Object Oriented Programming | | The Complete Reference Java | | Internet Programming | | Web Programming | Atomic Operations - java.util.concurrent.atomic

Chapter: Java The Complete Reference - The Java Library - The Concurrency Utilities

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Atomic Operations - java.util.concurrent.atomic

java.util.concurrent.atomic offers an alternative to the other synchronization features when reading or writing the value of some types of variables.

Atomic Operations

java.util.concurrent.atomic offers an alternative to the other synchronization features when reading or writing the value of some types of variables. This package offers methods that get, set, or compare the value of a variable in one uninterruptible (that is, atomic) operation. This means that no lock or other synchronization mechanism is required.

Atomic operations are accomplished through the use of classes, such as AtomicInteger and AtomicLong, and methods such as get( ), set( ), compareAndSet( ), decrementAndGet( ), and getAndSet( ), which perform the action indicated by their names.

 

Here is an example that demonstrates how access to a shared integer can be synchronized by the use of AtomicInteger:

 

// A simple example of Atomic.

 

import java.util.concurrent.atomic.*;

class AtomicDemo {

 

public static void main(String args[]) { new AtomThread("A");

 

new AtomThread("B"); new AtomThread("C");

}

 

}

 

class Shared {

 

static AtomicInteger ai = new AtomicInteger(0);

 

}

 

// A thread of execution that increments count.

class AtomThread implements Runnable {

 

String name;

 

AtomThread(String n) { name = n;

 

new Thread(this).start();

 

}

 

public void run() {

 

System.out.println("Starting " + name);

 

for(int i=1; i <= 3; i++) System.out.println(name + " got: " +

 

Shared.ai.getAndSet(i));

 

}

 

}

 

In the program, a static AtomicInteger named ai is created by Shared. Then, three threads of type AtomThread are created. Inside run( ), Shared.ai is modified by calling getAndSet( ). This method returns the previous value and then sets the value to the one passed as an argument. The use of AtomicInteger prevents two threads from writing to ai at the same time.

In general, the atomic operations offer a convenient (and possibly more efficient) alternative to the other synchronization mechanisms when only a single variable is involved. Beginning with JDK 8, java.util.concurrent.atomic also provides four classes that support lock-free cumulative operations. These are DoubleAccumulator, DoubleAdder, LongAccumulator, and LongAdder. The accumulator classes support a series of user-specified operations. The adder classes maintain a cumulative sum.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.