Atomic variables in Java

In this tutorial, we will learn what is the atomic variable, how to use it in Java.

When we use one variable in many threads and those threads use that variable concurrency in this situation may be inconsistency happens for solving this problem we can create a class for control, also we can use syncronized and we can use an atomic variable.

Atomic variable: Atomic variable work like atomicity when the program working it should execute all operation or none of them, in this situation all atomic variables should change or none of them.

Creating own class for one thread working but for many threads, we should use a synchronized or atomic variable.
In the synchronized locking method is used this locking method is not lightweight this is the first disadvantage.
The second disadvantage is when one thread using a variable, all other threads which need this variable should wait, and all of them cannot do any other work during the waiting time.

Type Of Atomic Variable class

  1. AtomicInteger
  2. AtomicLong
  3. AtomicBoolean
  4. AtomicReference

All these classes have these methods get(), set(), getAndSet(), and they support compare and swap operation also. We can find all these classes in java.util.concurrent.atomic package.

Example Atomic variable in Java

Below is the example in the Java program:

import java.util.concurrent.atomic.AtomicInteger;

public class Codespeedy {
    public static void main(String args[])
         AtomicInteger at = new AtomicInteger(); //create atomic variable
         at.set(5);  // set value
         System.out.println(at.decrementAndGet()); // decrement and return value
         System.out.println(at.incrementAndGet()); // increment and return value
         System.out.println(at.getAndDecrement()); // first return after that decrement
         System.out.println(at.getAndAdd(67));   // get value and add with  the passing parameter
         System.out.println(at.get()); // get value

Look at the above program. In this code, we can see a simple example of Atomic variables in Java. You can read the comment in the code.

Also, read:

Below is the output of our program:


Leave a Reply

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