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.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.