Atomic classes
Atomic classes (AtomicInteger, AtomicLong, AtomicReference, and the rest) expose single-variable updates that are thread-safe without a lock. incrementAndGet and compareAndSet are the usual operations.
Detailed Explanation
A volatile int is visible but count++ is still three steps. AtomicInteger makes increment one atomic operation. Under the hood it uses compare-and-swap (CAS): read the current value, compute the next, write it only if the field is still what we read. If another thread won, retry.
The family includes AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference<T>, arrays (AtomicIntegerArray), field updaters, and LongAdder / LongAccumulator for high-contention counters. LongAdder spreads stripes and sums them; it is faster than AtomicLong when many threads increment and you read rarely (the common pool's counters work this way).
updateAndGet and accumulateAndGet take a lambda. The lambda may run more than once if CAS fails, so it must be side-effect free. compareAndSet returns whether you won; spinning on it is a lock-free loop you should keep short.
You reach for an atomic when the shared state is one variable (or one reference to an immutable snapshot). You reach for a lock when you must update two fields together: two atomics do not make a transaction. You reach for ConcurrentHashMap when the state is a map.
The cost of CAS under heavy contention is wasted retries. LongAdder or a lock may win. The cost of AtomicReference to a mutable object is a false sense of safety: the reference swap is atomic, mutating the object is not. Publish immutable objects or lock.
weakCompareAndSet may fail spuriously. Use compareAndSet unless you are writing a specialized retry loop and know why. Memory effects: a successful atomic update is a volatile write; a failed CAS is not a reliable publication by itself.
Code Examples
import java.util.concurrent.atomic.AtomicInteger;
public class Hits {
public static void main(String[] args) throws InterruptedException {
AtomicInteger hits = new AtomicInteger();
Thread t = new Thread(() -> {
for (int i = 0; i < 10_000; i++) {
hits.incrementAndGet();
}
});
t.start();
for (int i = 0; i < 10_000; i++) {
hits.incrementAndGet();
}
t.join();
System.out.println(hits.get()); // prints: 20000
}
}import java.util.concurrent.atomic.AtomicReference;
public class Swap {
record Config(int timeoutMs) {}
public static void main(String[] args) {
AtomicReference<Config> ref = new AtomicReference<>(new Config(100));
ref.updateAndGet(c -> new Config(c.timeoutMs() * 2));
System.out.println(ref.get().timeoutMs()); // prints: 200
}
}Common Gotchas
Two `AtomicInteger`s are not updated together
use one lock or one atomic reference to an immutable pair.
Lambdas in `updateAndGet` must be pure
they can run more than once.
`LongAdder` is better than `AtomicLong` for hot increments and rare reads
`LongAdder` is better than `AtomicLong` for hot increments and rare reads
Atomic reference to a mutable object does not protect the object's fields
Atomic reference to a mutable object does not protect the object's fields