The knowledge sharing zone -

Use of Atomic variables in java

This page contains the details about Atomic Variables of Java, Use of atomic variables, How it works, Application of atomic variable with examples and sample programs.

Atomic variables in java

To understand the atomic variables in java, First you need to understand some basic concepts Like : Race condition / Problem with synchronization / Atomicity / Atomic or Non-interruptible operation :

Race condition

  • When multiple threads access the same resource (ex. an object's instance variables), and can produce corrupted data if one thread "races in" too quickly before an operation that should be "atomic" has completed.
  • See the below image for more understanding of the same :


  • Race condition can cause Account Overdraw, And to prevent account-overdraw we can use the Atomic Operation.

Atomic operation

  • Atomic operation is set of instructions which is expected to be executed as a whole or none at all.
  • The atomic operation is visible to the rest of the program only when it is complete.
  • To prevent the account overdraw problem, We must guarantee that the two steps of the withdrawal :-
    1. Checking the balance and
    2. Making the withdrawal, are never split apart.
  • We need them to always be performed as one operation, even when the thread falls asleep in between step 1 and step 2.


  • You can't guarantee that a single thread will stay running throughout the entire atomic operation.
  • But you can guarantee that even if the thread running the atomic operation moves in and out of the running state, no other running thread will be able to act on the same data.

Problem with synchronization

  • Synchronization carries overhead.
  • Use it where it is necessary, but never add synchronized to all of the methods just to be safe.
  • Some standards prefer synchronization on a method level where possible. Others recommends locking specific objects for greater control.

Atomic variables

  • In Java, java.util.concurrent.atomic package facilitates the use of atomic variables in a concurrent environment.
  • In other words, We can say that this package offers an alternative to the other synchronization features when reading or writing the value of some types of variables.
  • We can use it to efficiently update the value of a variable without the use of locks any other synchronization mechanism.
  • For that it provides following classes :
    • AtomicBoolean
    • AtomicInteger
    • AtomicLong
    • AtomicLongArray
    • AtomicReference
    • AtomicMarkableReference
    • AtomicStampedReference etc.
  • And methods, Like:
    • compareAndSet()
    • decrementAndGet()
    • getAndSet() etc.  these methods execute as a single, non-interruptible operation.


atomic variable example in java

Following program demonstrates, How the access to a shared integer can be synchronized by the use of AtomicInteger :

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicVariableDemo {

    public static void main(String args[]) throws InterruptedException {
        // 1. Create three incrementor threads, all of them uses SharedCounter
        Thread aThread = new Thread(new IncrementorThread(), "A");
        Thread bThread = new Thread(new IncrementorThread(), "B");
        Thread cThread = new Thread(new IncrementorThread(), "C");

        // 2. Each thread increments the counter by 1 for 100 times

        // 3. We have used Atomic counter & non-atomic counter.
        // Wait until all the threads completes.

        // 4. Only atomic variable gives the correct counts.
        System.out.println("Atomic counter : "
                + SharedCounter.atomicCounter.get());
        System.out.println("Non atomic counter : " + SharedCounter.counter);

 * Static & Non-static counters.
class SharedCounter {
    static AtomicInteger atomicCounter = new AtomicInteger(0);
    static int counter = 0;

 * This thread increments the counter by 1 for 100 times.
class IncrementorThread implements Runnable {

    public void run() {
        try {
            for (int i = 0; i < 100; i++) {

        } catch (InterruptedException e) {
// Output :
// Atomic counter : 300
// Non atomic counter : 293

Applications of atomic variable in java

  • You can implement thread safe counters so that it can be incremented from different execution threads.

You would also like to read:

Lock vs Atomic variables in java

Comments :

Name :
Email :
Comment :
Verify Text :
capch image, refresh page if not loaded somehow