Java Atomic Classes
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
intloses updates whenever the two threads overlap, so its total is too low. incrementAndGet()reads, adds and writes as one atomic step, so theAtomicIntegeralways 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-whileloop is the classic CAS pattern: read the current value, try to replace it, and retry if another thread got there first. Methods likeincrementAndGet()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.
| Method | Changes value by | Returns |
|---|---|---|
get() / set(v) | – / sets to v | current value / nothing |
incrementAndGet() | +1 | new value |
getAndIncrement() | +1 | old value |
decrementAndGet() | −1 | new value |
getAndDecrement() | −1 | old value |
addAndGet(delta) | +delta | new value |
getAndAdd(delta) | +delta | old value |
getAndSet(v) | sets to v | old value |
compareAndSet(expect, v) | sets to v if equal to expect | true/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++countand returns the new value;getAndIncrement()works likecount++and returns the old one.addAndGet()accepts negative numbers, so it also covers subtraction.AtomicLongis used for values that can grow beyond theintlimit 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.
| Method | Function | Example |
|---|---|---|
updateAndGet(fn) | x -> newX | double the value |
getAndUpdate(fn) | x -> newX | same, returns the old value |
accumulateAndGet(v, fn) | (x, v) -> newX | keep the maximum |
getAndAccumulate(v, fn) | (x, v) -> newX | same, 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 seestruealready stored, fails, and returnsfalse. - A plain
booleanwithif (!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 currentWallet, builds a new one withdeposit(), and swaps it in with CAS. If another thread swapped first, it retries with the newer wallet.- Because
Walletis 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==, notequals(). 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.
LongAdderis much faster here because threads rarely fight over the same memory location.sum()is not an atomic snapshot while updates are still happening, soLongAdderhas nocompareAndSet(). Use it for counting, andAtomicLongwhen you need the exact value at each step, such as IDs.
| Class | Best for |
|---|---|
AtomicInteger / AtomicLong | Counters you read often, IDs, CAS logic |
LongAdder / DoubleAdder | High-traffic counters and sums |
LongAccumulator | High-traffic max, min or custom combine |
AtomicBoolean | One-time actions, on/off flags |
AtomicReference | Swapping 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:
- Unique IDs.
getAndIncrement()on anAtomicLonghands each request a different ID from 1000 to 1199, even when ten threads ask at once. - Hot counters.
totalRequestsandfailedRequestsare updated by every request but read only in the report, which is exactly whatLongAdderis built for. - Rise and fall.
activeConnectionsgoes up on entry and down infinally, so it returns to 0.accumulateAndGet(active, Math::max)records the peak, 10, the pool size. - Maximum with LongAccumulator.
slowestMskeeps the largest duration seen, 64 ms, using the same idea asLongAdderfor maximum values. - Last error.
AtomicReference<String>is replaced atomically, so the report always shows one complete message. - Shutdown flag. Setting
acceptingRequeststofalsemakes later calls return immediately, so the extra/homerequest 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.