Atomic Operation and Atomic Classes
Atomic Operation
An Atomic Operation is widely known in Concurrency as an operation that performs a single unit of work without any possibility of interference from another operation.
A classic example to illustrate Atomic Operation would be two users making use of the the same application to print a statement - Atomic Operation will allow both users to print the statement by synchronising the requests and running them individually. First user clicks print, then second user clicks print - Printer Driver will synchronise the requests and run each request as its own process.
Atomic Variables
Atomic Variables belong to the java.util.concurrent.atomic package and considered primitive variables that are designed to be safely used in multi-threaded processes.
Atomic Variables provide operation that cannot be interfered by any multiple-threads and are guaranteed to execute using machine-level operation and modern processors.
They are helpful in avoiding overhead synchronisation on a single primitive variable and is therefore more efficient than standard synchronisation / locking mechanisms.
We find the following classes in the java.util.concurrent.atomic package as primitive variables:
AtomicBoolean
AtomicInteger
Atomic Long
And the following Atomic methods:
incrementAndGet() - Atomically increases the current value by one
decrementAndGet() - Atomically decreases the current value by one
compareAndSet() - Atomically results 'true' if successful or 'false' if not
Let's take a look at Atomic Operations and Variables in the following example, A thread-safe counter using AtomicInteger.
public class SafeCounterWithoutLock {
private final AtomicInteger counter = new AtomicInteger(0);
public int getValue() {
return counter.get();
}
public void increment() {
while(true) {
int existingValue = getValue();
int newValue = existingValue + 1;
if(counter.compareAndSet(existingValue, newValue)) {
return;
}
}
}
}
In the example, we see within the SafeCounterWithoutLock class that we have declared an AtomicInteger as counter. The class also contains the method to return the counter value. In the increment method, we apply the compareAndSet() method which will result in a true / false output. The counter will only increase by one if compareAndSet() results in true.
Thank you to GeeksforGeeks.com, Vogella.com, Baeldung.com and codejava.net for the resource, you can read up more information on Atomic Operations and Variables by clicking on the site links.
Comments
Post a Comment