Java Atomic Classes

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 199 of 306

Java atomic classes such as AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference hold a single value that many threads can read and update safely without locks. Each update, for example "add one", happens as one indivisible (atomic) step, so no thread can see or overwrite a half-finished change.

The classes live in the java.util.concurrent.atomic package. They are faster and simpler than synchronized for counters, flags, ID generators and other single shared values.


Why Java Atomic Classes Are Needed

The statement count++ looks like one operation, but the CPU performs three: read the value, add one, write it back. When two threads run it at the same time, both can read the same old value and one increment is lost. This is a race condition.

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicVsInt {
    static int plainCount = 0;                                // not thread-safe
    static AtomicInteger atomicCount = new AtomicInteger();   // thread-safe

    public static void main(String[] args) throws InterruptedException {
        Runnable work = () -> {
            for (int i = 0; i < 100_000; i++) {
                plainCount++;                    // read, add, write: three steps
                atomicCount.incrementAndGet();   // one atomic step
            }
        };

        Thread first = new Thread(work);
        Thread second = new Thread(work);
        first.start();
        second.start();
        first.join();
        second.join();

        System.out.println("Expected      : 200000");
        System.out.println("int count     : " + plainCount);
        System.out.println("AtomicInteger : " + atomicCount.get());
    }
}

Output from one run (the int value changes every time):

Expected      : 200000
int count     : 137412
AtomicInteger : 200000

How it works:

  • Both threads increment both counters 100,000 times.
  • The plain int loses updates whenever the two threads overlap, so its total is too low.
  • incrementAndGet() reads, adds and writes as one atomic step, so the AtomicInteger always reaches exactly 200,000.

How Atomic Classes Work: Compare-and-Set (CAS)

Atomic classes do not use locks. They rely on a CPU instruction called compare-and-set (CAS): "if the value is still expected, set it to newValue; otherwise do nothing and tell me it failed". If another thread changed the value first, the atomic class simply reads the new value and tries again.

Syntax

boolean changed = atomicValue.compareAndSet(expectedValue, newValue);
import java.util.concurrent.atomic.AtomicInteger;

public class CompareAndSetDemo {
    public static void main(String[] args) {
        AtomicInteger seatsLeft = new AtomicInteger(3);

        boolean first = seatsLeft.compareAndSet(3, 2);  // value is 3, so it becomes 2
        System.out.println("CAS(3 -> 2): " + first + ", seats = " + seatsLeft.get());

        boolean second = seatsLeft.compareAndSet(3, 2); // value is 2 now, not 3
        System.out.println("CAS(3 -> 2): " + second + ", seats = " + seatsLeft.get());

        // A CAS loop: retry until our update wins
        int current;
        do {
            current = seatsLeft.get();
        } while (!seatsLeft.compareAndSet(current, current - 1));
        System.out.println("After CAS loop, seats = " + seatsLeft.get());
    }
}

Output:

CAS(3 -> 2): true, seats = 2
CAS(3 -> 2): false, seats = 2
After CAS loop, seats = 1

How it works:

  • The first compareAndSet(3, 2) succeeds because the value really is 3.
  • The second one fails, because the value is already 2. Nothing changes, and the method returns false.
  • The do-while loop is the classic CAS pattern: read the current value, try to replace it, and retry if another thread got there first. Methods like incrementAndGet() use this pattern internally.

AtomicInteger and AtomicLong Methods

AtomicInteger and AtomicLong have the same methods; one wraps an int, the other a long. The method name tells you whether you get the value before or after the change.

MethodChanges value byReturns
get() / set(v)– / sets to vcurrent value / nothing
incrementAndGet()+1new value
getAndIncrement()+1old value
decrementAndGet()−1new value
getAndDecrement()−1old value
addAndGet(delta)+deltanew value
getAndAdd(delta)+deltaold value
getAndSet(v)sets to vold value
compareAndSet(expect, v)sets to v if equal to expecttrue/false
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class AtomicMethodsDemo {
    public static void main(String[] args) {
        AtomicInteger stock = new AtomicInteger(10);

        System.out.println("incrementAndGet : " + stock.incrementAndGet()); // 11
        System.out.println("getAndIncrement : " + stock.getAndIncrement()); // returns 11, now 12
        System.out.println("now             : " + stock.get());
        System.out.println("addAndGet(-5)   : " + stock.addAndGet(-5));     // 7
        System.out.println("getAndAdd(3)    : " + stock.getAndAdd(3));      // returns 7, now 10
        System.out.println("getAndSet(0)    : " + stock.getAndSet(0));      // returns 10, now 0
        System.out.println("final           : " + stock.get());

        AtomicLong bytesDownloaded = new AtomicLong();
        bytesDownloaded.addAndGet(3_000_000_000L); // bigger than int can hold
        System.out.println("bytes           : " + bytesDownloaded.get());
    }
}

Output:

incrementAndGet : 11
getAndIncrement : 11
now             : 12
addAndGet(-5)   : 7
getAndAdd(3)    : 7
getAndSet(0)    : 10
final           : 0
bytes           : 3000000000

How it works:

  • incrementAndGet() works like ++count and returns the new value; getAndIncrement() works like count++ and returns the old one.
  • addAndGet() accepts negative numbers, so it also covers subtraction.
  • AtomicLong is used for values that can grow beyond the int limit of about 2.1 billion.

updateAndGet and accumulateAndGet

For updates more complex than adding a number, Java 8 added methods that take a function. The atomic class runs the function inside a CAS loop, so the whole update is atomic.

MethodFunctionExample
updateAndGet(fn)x -> newXdouble the value
getAndUpdate(fn)x -> newXsame, returns the old value
accumulateAndGet(v, fn)(x, v) -> newXkeep the maximum
getAndAccumulate(v, fn)(x, v) -> newXsame, returns the old value
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class UpdateAccumulateDemo {
    public static void main(String[] args) {
        AtomicInteger highestScore = new AtomicInteger(0);
        AtomicInteger level = new AtomicInteger(1);
        int[] scores = {420, 980, 615, 1205, 870, 1190};

        try (ExecutorService players = Executors.newFixedThreadPool(3)) {
            for (int score : scores) {
                // keep the larger of the stored value and this score
                players.submit(() -> highestScore.accumulateAndGet(score, Math::max));
            }
        }
        System.out.println("Highest score: " + highestScore.get());

        // updateAndGet: double the level, but never above 10
        for (int i = 0; i < 5; i++) {
            System.out.print(level.updateAndGet(current -> Math.min(current * 2, 10)) + " ");
        }
        System.out.println();
    }
}

Output:

Highest score: 1205
2 4 8 10 10 

How it works:

  • Three threads report scores at the same time. accumulateAndGet(score, Math::max) atomically keeps the larger value, so the highest score is never overwritten by a lower one.
  • updateAndGet() applies the lambda to the current value: 1 → 2 → 4 → 8 → 10 → 10.

Note: The function you pass may be called more than once if another thread wins the race and the CAS has to be retried. Keep it fast and free of side effects such as printing or saving to a database.


AtomicBoolean: Thread-Safe Flags

AtomicBoolean holds a true/false flag. Its compareAndSet(false, true) is a reliable way to make sure something happens exactly once, even if many threads try at the same moment.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicBooleanDemo {
    private static final AtomicBoolean initialized = new AtomicBoolean(false);

    static void initDatabase() {
        // only the first thread to flip the flag runs the setup
        if (initialized.compareAndSet(false, true)) {
            System.out.println(Thread.currentThread().getName() + " runs the one-time database setup");
        } else {
            System.out.println(Thread.currentThread().getName() + " skips setup (already done)");
        }
    }

    public static void main(String[] args) {
        try (ExecutorService executor = Executors.newFixedThreadPool(4)) {
            for (int i = 0; i < 4; i++) {
                executor.submit(AtomicBooleanDemo::initDatabase);
            }
        }
        System.out.println("initialized = " + initialized.get());
    }
}

Output from one run (which thread wins can change):

pool-1-thread-2 runs the one-time database setup
pool-1-thread-1 skips setup (already done)
pool-1-thread-3 skips setup (already done)
pool-1-thread-4 skips setup (already done)
initialized = true

How it works:

  • All four threads call compareAndSet(false, true) at about the same time.
  • Exactly one succeeds and gets true. Every other call sees true already stored, fails, and returns false.
  • A plain boolean with if (!done) { done = true; ... } could let two threads through, because the check and the write are separate steps.

AtomicReference: Atomic Updates to Objects

AtomicReference<V> holds a reference to any object. Combined with immutable objects, such as Java records, it lets threads replace a whole object atomically.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceDemo {
    // Immutable: every change creates a new Wallet
    record Wallet(String owner, int balance, int transactions) {
        Wallet deposit(int amount) {
            return new Wallet(owner, balance + amount, transactions + 1);
        }
    }

    public static void main(String[] args) {
        AtomicReference<Wallet> wallet = new AtomicReference<>(new Wallet("Kavin", 0, 0));

        try (ExecutorService executor = Executors.newFixedThreadPool(4)) {
            for (int i = 0; i < 1000; i++) {
                executor.submit(() -> wallet.updateAndGet(w -> w.deposit(10)));
            }
        }

        Wallet result = wallet.get();
        System.out.println(result);
        System.out.println("Balance matches transactions? "
                + (result.balance() == result.transactions() * 10));
    }
}

Output:

Wallet[owner=Kavin, balance=10000, transactions=1000]
Balance matches transactions? true

How it works:

  • updateAndGet() reads the current Wallet, builds a new one with deposit(), and swaps it in with CAS. If another thread swapped first, it retries with the newer wallet.
  • Because Wallet is immutable, no thread ever sees a wallet whose balance is updated but whose transaction count is not.
  • After 1,000 deposits of 10, both fields agree: 10,000 and 1,000.

Note: AtomicReference.compareAndSet() compares references with ==, not equals(). Two different objects with equal content are not considered the same.


AtomicIntegerArray: Atomic Array Elements

An AtomicInteger[] array would need one object per slot. AtomicIntegerArray (and AtomicLongArray, AtomicReferenceArray) stores the values compactly and offers atomic operations on each index.

import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicIntegerArray;

public class AtomicArrayDemo {
    public static void main(String[] args) {
        String[] ratings = {"5", "4", "5", "3", "5", "4", "1", "5", "4", "2"};
        AtomicIntegerArray starCounts = new AtomicIntegerArray(6); // index 1..5 used

        try (ExecutorService executor = Executors.newFixedThreadPool(3)) {
            for (String rating : ratings) {
                executor.submit(() -> starCounts.incrementAndGet(Integer.parseInt(rating)));
            }
        }

        for (int stars = 5; stars >= 1; stars--) {
            char[] bar = new char[starCounts.get(stars)];
            Arrays.fill(bar, '#');
            System.out.println(stars + " stars: " + new String(bar) + " (" + starCounts.get(stars) + ")");
        }
    }
}

Output:

5 stars: #### (4)
4 stars: ### (3)
3 stars: # (1)
2 stars: # (1)
1 stars: # (1)

How it works:

  • Each rating increments one slot of the array: incrementAndGet(index).
  • Different threads can update different slots, or the same slot, without losing counts.
  • The loop prints a small text histogram from the final counts.

LongAdder: Fast Counters Under Heavy Load

When many threads hammer the same AtomicLong, their CAS attempts keep failing and retrying. LongAdder avoids this by giving threads separate internal cells and adding them up only when you ask for the total with sum(). It is the best choice for statistics counters that are updated often and read rarely.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class LongAdderDemo {
    static long timeIt(Runnable increment) {
        long start = System.nanoTime();
        try (ExecutorService executor = Executors.newFixedThreadPool(8)) {
            for (int t = 0; t < 8; t++) {
                executor.submit(() -> {
                    for (int i = 0; i < 2_000_000; i++) {
                        increment.run();
                    }
                });
            }
        }
        return (System.nanoTime() - start) / 1_000_000;
    }

    public static void main(String[] args) {
        AtomicLong atomicHits = new AtomicLong();
        LongAdder adderHits = new LongAdder();

        long atomicMs = timeIt(atomicHits::incrementAndGet);
        long adderMs = timeIt(adderHits::increment);

        System.out.println("AtomicLong: " + atomicHits.get() + " hits in " + atomicMs + " ms");
        System.out.println("LongAdder : " + adderHits.sum() + " hits in " + adderMs + " ms");
    }
}

Output from one run on an 8-core machine (times vary):

AtomicLong: 16000000 hits in 312 ms
LongAdder : 16000000 hits in 41 ms

How it works:

  • Eight threads add 2 million hits each to both counters. Both end with exactly 16,000,000.
  • LongAdder is much faster here because threads rarely fight over the same memory location.
  • sum() is not an atomic snapshot while updates are still happening, so LongAdder has no compareAndSet(). Use it for counting, and AtomicLong when you need the exact value at each step, such as IDs.
ClassBest for
AtomicInteger / AtomicLongCounters you read often, IDs, CAS logic
LongAdder / DoubleAdderHigh-traffic counters and sums
LongAccumulatorHigh-traffic max, min or custom combine
AtomicBooleanOne-time actions, on/off flags
AtomicReferenceSwapping immutable objects

Real-World Example: Web Server Request Metrics

A web server tracks live statistics from many request-handling threads: total requests, active connections, the slowest response, the last error, and unique request IDs. Each metric uses the atomic class that fits it best.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;

public class ServerMetrics {
    private final AtomicLong nextRequestId = new AtomicLong(1000);   // unique IDs
    private final LongAdder totalRequests = new LongAdder();          // hot counter
    private final LongAdder failedRequests = new LongAdder();
    private final AtomicInteger activeConnections = new AtomicInteger();
    private final AtomicInteger peakConnections = new AtomicInteger();
    private final LongAccumulator slowestMs = new LongAccumulator(Math::max, 0);
    private final AtomicReference<String> lastError = new AtomicReference<>("none");
    private final AtomicBoolean acceptingRequests = new AtomicBoolean(true);

    void handle(String path, int durationMs) {
        if (!acceptingRequests.get()) {
            return; // server is shutting down
        }
        long requestId = nextRequestId.getAndIncrement();
        int active = activeConnections.incrementAndGet();
        peakConnections.accumulateAndGet(active, Math::max);
        try {
            Thread.sleep(durationMs); // simulated work
            if (path.equals("/api/pay") && requestId % 7 == 0) {
                throw new IllegalStateException("payment gateway timeout (request " + requestId + ")");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (IllegalStateException e) {
            failedRequests.increment();
            lastError.set(e.getMessage());
        } finally {
            totalRequests.increment();
            slowestMs.accumulate(durationMs);
            activeConnections.decrementAndGet();
        }
    }

    void printReport() {
        System.out.println("Total requests    : " + totalRequests.sum());
        System.out.println("Failed requests   : " + failedRequests.sum());
        System.out.println("Active now        : " + activeConnections.get());
        System.out.println("Peak connections  : " + peakConnections.get());
        System.out.println("Slowest response  : " + slowestMs.get() + " ms");
        System.out.println("Next request id   : " + nextRequestId.get());
        System.out.println("Last error        : " + lastError.get());
    }

    public static void main(String[] args) {
        ServerMetrics metrics = new ServerMetrics();
        String[] paths = {"/home", "/courses", "/api/pay", "/login"};

        try (ExecutorService workers = Executors.newFixedThreadPool(10)) {
            for (int i = 0; i < 200; i++) {
                String path = paths[i % paths.length];
                int durationMs = 5 + (i * 37) % 60; // 5..64 ms, varies per request
                workers.submit(() -> metrics.handle(path, durationMs));
            }
        }
        metrics.acceptingRequests.set(false); // stop accepting new work
        metrics.handle("/home", 10);          // ignored
        metrics.printReport();
    }
}

Output from one run (failed requests and the last error depend on thread timing):

Total requests    : 200
Failed requests   : 7
Active now        : 0
Peak connections  : 10
Slowest response  : 64 ms
Next request id   : 1200
Last error        : payment gateway timeout (request 1197)

How it works:

  1. Unique IDs. getAndIncrement() on an AtomicLong hands each request a different ID from 1000 to 1199, even when ten threads ask at once.
  2. Hot counters. totalRequests and failedRequests are updated by every request but read only in the report, which is exactly what LongAdder is built for.
  3. Rise and fall. activeConnections goes up on entry and down in finally, so it returns to 0. accumulateAndGet(active, Math::max) records the peak, 10, the pool size.
  4. Maximum with LongAccumulator. slowestMs keeps the largest duration seen, 64 ms, using the same idea as LongAdder for maximum values.
  5. Last error. AtomicReference<String> is replaced atomically, so the report always shows one complete message.
  6. Shutdown flag. Setting acceptingRequests to false makes later calls return immediately, so the extra /home request is not counted.

Atomic classes protect one value at a time. When several values must change together, use a lock, synchronization, or an immutable object inside an AtomicReference. For thread-safe maps and queues, see Java Concurrent Collections.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Atomic Classes and get answers drawn from it.

Signed-in readers only.