What is AtomicInteger / AtomicReference in Java?

In Java, AtomicInteger and AtomicReference are classes from the java.util.concurrent.atomic package that provide a way to work with integers and object references in a thread-safe manner. These classes are part of the Java Concurrency framework and are designed to handle scenarios where multiple threads need to read and modify shared variables without the use of explicit synchronization.

AtomicInteger

AtomicInteger allows you to work with an integer value atomically. This means that you can perform operations such as incrementing, decrementing, or setting a new value in a way that guarantees that no other thread will interfere with those operations, thus preventing inconsistent states.

AtomicReference

The AtomicReference class provides similar functionality for object references. It allows you to store, retrieve, and update references atomically, which is useful in multithreaded applications where multiple threads may be accessing and modifying the same object.

Example


import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicExample {
    public static void main(String[] args) {
        // Using AtomicInteger
        AtomicInteger atomicInt = new AtomicInteger(0);
        System.out.println("Initial Value: " + atomicInt.get());
        atomicInt.incrementAndGet(); // Atomic increment
        System.out.println("After Increment: " + atomicInt.get());

        // Using AtomicReference
        AtomicReference atomicRef = new AtomicReference<>("Initial");
        System.out.println("Initial Reference: " + atomicRef.get());
        atomicRef.set("Updated"); // Atomic set
        System.out.println("After Update: " + atomicRef.get());
    }
}
    

AtomicInteger AtomicReference Java concurrency thread-safe multithreading atomic operations