Member-only story
Java Multithreading, Concurrency, and Parallelism — Part 18
The atomic variables — AtomicXXX classes
The java.util.concurrent.atomic
package provides several atomic classes for different data types, such as AtomicInteger
, AtomicLong
, AtomicBoolean
, and AtomicReference
, to name a few.
All these AtomicXXX classes internally use CASing — The Compare-and-Swap, which we have already seen in Part 17.2. In this article, we will go a little deeper. So, let’s jump right in.
To start with, we will implement an atomic counter using AtomicInteger
class. Look at the below AtomicCounter
class which is used by multiple threads concurrently.
The main thing in the AtomicCounter
class that is of our interest is counter.getAndIncrement()
at line 9. This method internally calls the getAndAddInt()
on an object of type sun.misc.Unsafe
class. This is the story till Java 8. From Java 9 this has been changed to jdk.internal.misc.Unsafe
. There are important reasons for this which are not of our concern for now. But there will be a separate article for it.
The Unsafe
class is a collection of methods for performing low-level, unsafe operations. So in our case, Unsafe.getAndAddInt()
method is what actually performs the low-level CAS…