Script Valley
Java: Complete Language Course
Concurrency and MultithreadingLesson 5.4

Java atomic classes and concurrent collections

AtomicInteger, AtomicLong, AtomicReference, CAS operation, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue, ArrayBlockingQueue, thread-safe collections

Atomic Classes and Concurrent Collections

Atomic classes provide thread-safe single-variable operations without locks, using CPU-level compare-and-swap (CAS). Concurrent collections replace synchronized wrappers with higher-throughput implementations designed for concurrent access patterns.

AtomicInteger โ€” Lock-Free Counter

import java.util.concurrent.atomic.AtomicInteger;

AtomicInteger count = new AtomicInteger(0);

ExecutorService pool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
    pool.submit(() -> count.incrementAndGet());
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println(count.get()); // always 1000

ConcurrentHashMap โ€” Thread-Safe Map

Map map = new ConcurrentHashMap<>();

// merge is atomic โ€” safe from multiple threads
map.merge("word", 1, Integer::sum);
map.merge("word", 1, Integer::sum);
System.out.println(map.get("word")); // 2

BlockingQueue โ€” Producer-Consumer

BlockingQueue queue = new ArrayBlockingQueue<>(100);

new Thread(() -> {
    try { queue.put("item"); }
    catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}).start();

new Thread(() -> {
    try { String item = queue.take(); System.out.println(item); }
    catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}).start();

Prefer AtomicInteger over synchronized for single-variable counters. Prefer ConcurrentHashMap over Collections.synchronizedMap() โ€” it allows concurrent reads and fine-grained segment locking for writes.

For high-contention counters across many threads, consider LongAdder over AtomicLong. LongAdder maintains multiple internal cells to reduce CAS contention, then sums them on read โ€” significantly faster when updates vastly outnumber reads.

For simple boolean flags shared between threads, AtomicBoolean provides the same CAS-based safety. Use AtomicReference<T> to atomically swap object references โ€” useful for publishing immutable snapshots of complex state without locks.

Up next

Java CompletableFuture for async non-blocking code

Sign in to track progress

Java atomic classes and concurrent collections โ€” Concurrency and Multithreading โ€” Java: Complete Language Course โ€” Script Valley โ€” Script Valley