Atomic Variables in Java

Atomic Variables in Java
In Java, We have a package java.util.concurrent.atomic. Atomic variables are the one which supports multiple operations on a single variable.

Atomic class has get() method, set() method and also compareandset() method.

Let us see some examples of using Atomic Integer, which is from package java.util.concurrent.AtomicInteger.

We are going to see,

get() – Getting the atomic variable value
set() – Setting the atomic variable value
compareAndSet() – Check the atomic variable value and set it to a new value
addAndGet() – This is similar to variable++
getAndAdd() – This is similar to ++variable
getAndIncrement() – This works similar to getAndAdd, But this increment by 1. (++variable)
incrementAndGet() – This works similar to addAndGet. But increments by 1 (variable++)
getAndDecrement() – This is similar to getAndAdd, This decrements value by 1 (–variable)
decrementAndGet() – This is similar to addAndGet, This decrements value by 1 (variable–)

If we want to subtract some value, We can use addAndGet(-value) / getAndAdd(-value)

Now let us see an example of all these above methods,


Leave a Reply

Your email address will not be published. Required fields are marked *