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.
