Atomic variables in Java

Atomic variables

 
An atomic variable is an instance of a class that encapsulates a single variable and supports lock-free, thread-safe operations on that variable, for example, AtomicInteger.

 

Need for Atomic variables

 
Refer the following program that increments the number of like for TopJavaTutorial.com with each user like.

non-atomic operation
 
This increment code may appear as a single line, but its not atomic and not safe.

The following operations happen at machine level for the increment :-

– load the variable from memory to register
– increment the variable
– load the updated value back in memory

There could be two or more threads that obtain the same value as they both retrieve the variable but haven’t incremented it yet.
Then those threads increment the counter to the same number.

We can this method as synchronized, but it will block thread execution.

 

Atomic classes

 
Atomic classes are built for thread-safety in concurrent environment.

Atomic classes are java.util.concurrent.atomic package.

They have methods to atomically increment and get updated values or compare and update variable.

The below code modifies the Visitor class to add an AtomicLong variable.

atomic operation

 

Atomic classes and methods

 
Commonly used Atomic classes are AtomicInteger, AtomicLong, AtomicBoolean, AtomicIntegerArray, AtomicLongArray, and Atomic-Reference.
 

Here are some commonly used methods in AtomicInteger class.
 

int addAndGet(int delta)

Atomically adds the given value to the current value.
 

int getAndAdd(int delta)

Atomically adds the given value to the current value.
 

int getAndDecrement()

Atomically decrements by one the current value.
 

int getAndIncrement()

Atomically increments by one the current value.
 

boolean compareAndSet(int expect, int update)

Atomically sets the value to the given updated value if the current value == the expected value.
 

int getAndAdd(int delta)

Atomically adds the given value to the current value.

 

Volatile vs Atomic

 
Using volatile keyword means that each individual read or write operation on that variable is atomic.

Volatile variables can’t define a sequence of operations (like read-compare/modify-write)
as an atomic operation.

For example, operations that requires more than one read/write(like increment as shown above example) are not atomic, since another thread may access the variable between the read and the write.

Atomic classes like AtomicInteger, AtomicLong etc provide atomic operations with proper synchronization.

 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

  1. Helpful

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: