Java Reference ยท Concurrency
Atomic classes: AtomicInteger, AtomicReference and LongAdder
Reference for java.util.concurrent.atomic: AtomicInteger, AtomicLong, AtomicReference, compareAndSet, updateAndGet, LongAdder and when to prefer them.
The classes in java.util.concurrent.atomic give you single variables with thread-safe operations that do not use locks. They rely on hardware compare-and-swap (CAS) instructions: an update succeeds only if the variable still holds the value you expected, otherwise you retry. Because no thread ever blocks, atomics scale well under moderate contention and cannot deadlock.
The main types are AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference<V>, plus array versions (AtomicIntegerArray, ...) and accumulators (LongAdder, LongAccumulator) that are faster under heavy contention.
AtomicInteger counter = new AtomicInteger(); counter.incrementAndGet(); // 1, atomically counter.compareAndSet(1, 10); // true: value was 1, is now 10
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class AtomicInteger extends Number public class AtomicReference<V> public class LongAdder extends Number
| Method | Description |
|---|---|
get(), set(v) |
Volatile read and write. |
getAndSet(v) |
Sets the value and returns the previous one. |
compareAndSet(expect, update) |
Sets to update only if the current value equals expect (== for references). Returns whether it succeeded. |
incrementAndGet(), getAndIncrement(), decrementAndGet(), addAndGet(d), getAndAdd(d) |
Arithmetic updates (AtomicInteger, AtomicLong). |
updateAndGet(fn), getAndUpdate(fn) |
Applies a function in a CAS loop. The function must be free of side effects since it may run more than once. |
accumulateAndGet(x, fn) |
Combines the current value with x. |
lazySet(v), getPlain(), getAcquire(), setRelease(v) |
Weaker memory orderings for experts. |
LongAdder.add(x), increment(), sum(), reset() |
Striped counter; sum() is not an atomic snapshot while updates run. |
Usage notes
- Atomic does not mean composable. Each call is atomic, but "check then act" over two calls is not.
if (n.get() < 10) n.incrementAndGet()can overshoot; useupdateAndGetorcompareAndSetin a loop. - Several variables need a lock. Atomics protect one variable. Invariants over two fields (a balance and a transaction count) need a lock or one immutable object in an
AtomicReference. AtomicReference.compareAndSetcompares identity. Two equal but distinct objects do not match. Use the same instance you read.- ABA problem. A CAS cannot tell that a value changed from A to B and back to A.
AtomicStampedReferenceandAtomicMarkableReferenceadd a version number or flag. LongAdderfor hot counters. Under many writers it spreads updates across cells and beatsAtomicLong; readingsum()is slower and only weakly consistent. UseAtomicLongwhen you need an exact value for decisions (sequence numbers).- Update functions must be pure.
updateAndGetretries on contention, so side effects (logging, I/O) can happen more than once. - Memory effects.
get/setact likevolatilereads and writes; every successful CAS is a full synchronization point for that variable. AtomicIntegeris not anInteger. It has noequals/hashCodeby value, so don't use it as a map key; it is mutable.