Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

AtomicInteger — atomic operations on int

AtomicInteger provides atomic operations on a single int value shared between threads. Learn reading, writing, incrementing, and conditional updates, including the limits of atomicity.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

import java.util.concurrent.atomic.AtomicInteger;
AtomicInteger counter = new AtomicInteger(0);
int updated = counter.incrementAndGet();
int current = counter.get();
counter.set(10);
boolean changed = counter.compareAndSet(10, 20);

java.util.concurrent.atomic.AtomicInteger holds one mutable int value, such as a counter shared between threads. It is not a general-purpose replacement for Integer. Entry scope: Java SE 21; neither the repository runtime nor the production runtime is attested.

AtomicInteger.incrementAndGet() atomically increases the value by one and returns the new value. AtomicInteger.get() reads the current value, while AtomicInteger.set(newValue) writes it and returns void. Reading and writing have volatile memory semantics.

AtomicInteger.compareAndSet(expectedValue, newValue) atomically compares the current value with expectedValue using ==. On a match, it writes newValue and returns true; otherwise, it leaves the value unchanged and returns false.

Atomic individual operations do not make entire sequences atomic: counter.set(counter.get() + 1) can lose another thread's update. Use counter.incrementAndGet() for incrementing. One object also does not make changes across multiple independent variables atomic.

Examples

import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {
        AtomicInteger counter = new AtomicInteger(0);
        System.out.println(counter.incrementAndGet());
        System.out.println(counter.get());
        counter.set(10);
        System.out.println(counter.compareAndSet(10, 20));
        System.out.println(counter.compareAndSet(10, 30));
        System.out.println(counter.get());
    }
}

Result

1
1
true
false
20

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources