Atomic Variables & Concurrent Collections
volatile, AtomicInteger/Long/Reference, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue
- Understand the Java Memory Model and the volatile guarantee
- Use Atomic classes for lock-free thread-safe counters
- Choose the right concurrent collection for producer-consumer patterns
A comprehensive study guide covering lock-free concurrency, the Compare-And-Swap operation, atomic classes, the volatile keyword, and thread-safe concurrent collections.
Table of Contents
- Ways to Achieve Concurrency
- Lock-Based vs Lock-Free Mechanisms
- Optimistic Concurrency Control — A Quick Recap
- Compare-And-Swap (CAS) Operation
- ABA Problem in CAS
- The Problem with Non-Atomic Operations
- Atomic Variables in Java
- How
AtomicIntegerInternally Uses CAS - The
volatileKeyword - Atomic vs Volatile — Key Differences
- Concurrent Collections in Java
- Interview Notes
- Practice Questions
- Summary Cheat Sheet
1. Ways to Achieve Concurrency
Overview
In Java, concurrency means allowing multiple threads to execute work simultaneously while keeping shared data consistent. There are exactly two fundamental approaches to achieving concurrency.
The Two Mechanisms
| # | Mechanism | Description | Examples |
|---|---|---|---|
| 1 | Lock-Based | Threads acquire a lock before entering a critical section. Only one thread proceeds at a time. | synchronized, ReentrantLock, ReadWriteLock, StampedLock, Semaphore |
| 2 | Lock-Free | No locks are used. Threads compete atomically at the CPU level. | AtomicInteger, AtomicBoolean, AtomicLong, AtomicReference |
2. Lock-Based vs Lock-Free Mechanisms
Lock-Based Mechanism
When a thread wants to access shared data, it first acquires a lock. Other threads that need the same resource must wait (block) until the lock is released. This guarantees that only one thread executes the critical section at a time.
Characteristics:
- Safe for complex business logic spanning multiple steps or multiple shared variables
- Threads block while waiting → context switching overhead
- Risk of deadlock if locks are acquired in inconsistent orders
- Risk of thread starvation if one thread monopolizes the lock
Lock-Free Mechanism
Instead of blocking, threads retry operations atomically using CPU-level hardware instructions (CAS). No thread ever blocks waiting for a lock.
Characteristics:
- No blocking, no context switching overhead for lock acquisition
- Works best for simple read → modify → update patterns on a single variable
- Can have liveness issues (a thread retrying infinitely if contention is very high — called livelock)
- Faster than lock-based in the specific use case it targets
3. Optimistic Concurrency Control A Quick Recap
Overview
Before diving into CAS, it helps to understand Optimistic Concurrency Control (OCC), which is the same conceptual idea applied at the database level. CAS is the hardware-level equivalent.
How OCC Works (Database Example)
Consider a database table with a row version column:
| Roll Number | Name | Row Version |
|---|---|---|
| 123 | Raj | 1 |
Scenario: Two threads read and try to update the same row simultaneously.
Key takeaway: OCC allows multiple readers but detects conflicts at write time using a version number. If a conflict is detected, the losing thread re-reads and retries. No locks are ever held.
4. Compare-And-Swap (CAS) Operation
Overview
Compare-And-Swap (CAS) is a low-level atomic instruction supported natively by all modern CPUs. It is the hardware foundation that makes lock-free programming possible in Java.
CAS is to hardware what Optimistic Concurrency Control is to databases. They solve the same problem at different levels of the system.
Definition
CAS is an atomic CPU instruction that performs three steps — read, compare, and conditionally write — as a single indivisible unit, even across multiple CPU cores.
Parameters
CAS accepts exactly three parameters:
| Parameter | Description |
|---|---|
| Memory Address (M) | The location in memory where the variable is stored |
| Expected Value (E) | The value you expect to currently be in that memory location |
| New Value (N) | The value you want to write if the expectation holds |
How CAS Works Step by Step
Detailed Example
1Memory M1 contains variable x = 102
3CAS(M1, expected=10, newValue=12)4
5Step 1: Load x from M1 → reads 106Step 2: Compare 10 (memory) == 10 (expected) → ✅ Match7Step 3: Write 12 to M1 → x is now 128Result: Success1CAS(M1, expected=10, newValue=15)2// Meanwhile, another thread changed x to 123
4Step 1: Load x from M1 → reads 125Step 2: Compare 12 (memory) == 10 (expected) → ❌ No match6Step 3: Nothing written7Result: Failure — caller must retryWhy CAS is Atomic
All modern CPUs implement CAS as a single hardware instruction (e.g., CMPXCHG on x86). The CPU guarantees that no other core can interfere between the load and the conditional store. This guarantee holds regardless of how many cores the CPU has.
5. ABA Problem in CAS
What is the ABA Problem?
The ABA problem occurs when a memory location's value changes from A → B → A between a thread's read and its CAS attempt. Because the value looks the same as the originally read value, CAS succeeds — even though the data was modified in the interim.
Example
1Thread 1 reads M1 → value is 10 (version A)2
3Meanwhile:4 Some thread changes M1 from 10 → 125 Another thread changes M1 from 12 → 10 (back to A)6
7Thread 1 runs CAS(M1, expected=10, newValue=13)8 Step 1: Load M1 → 10 ✅9 Step 2: Compare 10 == 10 → ✅ Match10 Step 3: Write 13 → succeeds11
12But Thread 1's "10" expectation was based on the ORIGINAL "10".13The memory has been changed and restored — Thread 1 doesn't know.Solution: Add a Version or Timestamp
Pair each value with a version counter (or timestamp). CAS then checks both the value AND the version.
| Event | Value | Version |
|---|---|---|
| Initial | 10 | 1 |
| Changed to 12 | 12 | 2 |
| Changed back to 10 | 10 | 3 |
Thread 1 originally read (value=10, version=1). When it attempts CAS, the memory holds (value=10, version=3). The version mismatch causes CAS to fail correctly.
Java provides AtomicStampedReference and AtomicMarkableReference to solve ABA:
1// AtomicStampedReference carries both value and integer stamp (version)2AtomicStampedReference<Integer> ref = new AtomicStampedReference<>(10, 1);3
4int[] stampHolder = new int[1];5int currentValue = ref.get(stampHolder); // reads value AND stamp6int currentStamp = stampHolder[0];7
8// CAS now requires both value and stamp to match9boolean success = ref.compareAndSet(10 currentValue, // expected value11 newValue, // new value12 currentStamp, // expected stamp13 currentStamp + 1 // new stamp14);AtomicStampedReference to guard against it.6. The Problem with Non-Atomic Operations
The `counter++` Illusion
A very common mistake is assuming counter++ is a single atomic operation. It is not.
What `counter++` Actually Does
The seemingly simple counter++ expands into three separate operations:
11. LOAD → Read the current value of counter from memory22. ADD → Increment the loaded value by 133. STORE → Write the incremented value back to memoryIn single-threaded code this is irrelevant. In multi-threaded code, another thread can slip between any of these three steps.
Demonstration: The Race Condition
1public class SharedResource {2 private int counter = 0;3
4 public void increment() {5 counter++; // NOT atomic — 3 steps!6 }7
8 public int get() {9 return counter;10 }11}1// Single-threaded: works perfectly2SharedResource resource = new SharedResource();3for (int i = 0; i < 400; i++) {4 resource.increment();5}6System.out.println(resource.get()); // Always 400 ✅1// Multi-threaded: BROKEN2SharedResource resource = new SharedResource();3
4Thread t1 = new Thread(() -> {5 for (int i = 0; i < 200; i++) resource.increment();6});7Thread t2 = new Thread(() -> {8 for (int i = 0; i < 200; i++) resource.increment();9});10
11t1.start();12t2.start();13t1.join();14t2.join();15
16System.out.println(resource.get()); // Might print 371, 385, 357... NOT 400 ❌Why the Output is Wrong Timeline Visualization
Both threads read 0, both compute 1, and both write 1. The second write overwrites the first. One increment is silently lost.
7. Atomic Variables in Java
Overview
Java's java.util.concurrent.atomic package provides a set of classes that wrap primitive types (and object references) and expose them through thread-safe, lock-free atomic operations built on CAS.
Available Atomic Classes
| Class | Wraps | Use Case |
|---|---|---|
AtomicInteger | int | Thread-safe integer counter/flag |
AtomicLong | long | Thread-safe long counter |
AtomicBoolean | boolean | Thread-safe boolean flag |
AtomicReference | any object | Thread-safe object reference updates |
AtomicIntegerArray | int[] | Thread-safe int array element updates |
AtomicLongArray | long[] | Thread-safe long array element updates |
AtomicStampedReference | object + stamp | ABA-safe reference updates |
AtomicMarkableReference | object + boolean | Reference with a mark bit |
Fixing the Counter Problem with `AtomicInteger`
1import java.util.concurrent.atomic.AtomicInteger;2
3public class SharedResource {4 // Replace plain int with AtomicInteger5 private AtomicInteger counter = new AtomicInteger(0);6
7 public void increment() {8 counter.incrementAndGet(); // Atomic! Internally uses CAS9 }10
11 public int get() {12 return counter.get();13 }14}1SharedResource resource = new SharedResource();2
3Thread t1 = new Thread(() -> {4 for (int i = 0; i < 200; i++) resource.increment();5});6Thread t2 = new Thread(() -> {7 for (int i = 0; i < 200; i++) resource.increment();8});9
10t1.start();11t2.start();12t1.join();13t2.join();14
15System.out.println(resource.get()); // Always 400 ✅Key `AtomicInteger` Methods
| Method | Description |
|---|---|
get() | Returns the current value |
set(int newValue) | Sets to the given value |
getAndIncrement() | Returns current value, then increments (post-increment) |
incrementAndGet() | Increments, then returns new value (pre-increment) |
getAndDecrement() | Returns current value, then decrements |
decrementAndGet() | Decrements, then returns new value |
addAndGet(int delta) | Adds delta, returns new value |
getAndAdd(int delta) | Returns current, then adds delta |
compareAndSet(int expected, int update) | CAS — sets if current == expected |
compareAndExchange(int expected, int update) | Like CAS but returns the witnessed value |
addAndGet(n) when you need to increment by a specific value other than 1.When to Use Atomic Classes
8. How `AtomicInteger` Internally Uses CAS
Internal Field: `value`
Inside AtomicInteger, there is a single field:
1private volatile int value;The volatile keyword here ensures that reads and writes to value go directly to main memory — no stale CPU cache copies. (More on volatile in Section 9.)
`incrementAndGet()` Internal Implementation
The method effectively does this (simplified from the JDK source):
1public final int incrementAndGet() {2 return unsafe.getAndAddInt(this, valueOffset, 1) + 1;3}Which internally loops:
1// Conceptual equivalent of the native CAS loop2public final int incrementAndGet() {3 for (;;) { // Spin until CAS succeeds4 int expected = get(); // Step 1: Read current value from memory5 int newValue = expected + 1; // Step 2: Compute new value6 if (compareAndSet(expected, newValue)) { // Step 3: CAS7 return newValue; // CAS succeeded — return8 }9 // CAS failed — another thread changed the value — retry10 }11}Step-by-Step Execution with Two Threads
`compareAndSet` The Raw CAS Call
You can call CAS directly on an AtomicInteger:
1AtomicInteger counter = new AtomicInteger(10);2
3// Only update if current value is 104boolean updated = counter.compareAndSet(10, 20);5System.out.println(updated); // true6System.out.println(counter.get()); // 207
8// Try again — current is now 20, not 109boolean updated2 = counter.compareAndSet(10, 30);10System.out.println(updated2); // false11System.out.println(counter.get()); // still 20The Native Layer
AtomicInteger.compareAndSet ultimately calls down to sun.misc.Unsafe.compareAndSwapInt, which is a native method implemented in C/C++ that maps directly to the CPU's CMPXCHG instruction (on x86). Java developers cannot access Unsafe directly; the atomic classes are the safe, public API surface for this capability.
9. The `volatile` Keyword
The CPU Cache Architecture Problem
To understand volatile, you must first understand how modern CPUs cache memory.
1┌──────────────────────────────────────────────────────┐2│ RAM │3│ (Main Memory) │4└─────────────────────────┬────────────────────────────┘5 │6 ┌────────────────┴────────────────┐7 │ │8┌────────▼────────┐ ┌────────▼────────┐9│ CPU Core 1 │ │ CPU Core 2 │10│ │ │ │11│ ┌───────────┐ │ │ ┌───────────┐ │12│ │ L1 Cache │ │ │ │ L1 Cache │ │13│ │ (fast) │ │ │ │ (fast) │ │14│ └───────────┘ │ │ └───────────┘ │15│ Thread 1 runs │ │ Thread 2 runs │16└─────────────────┘ └─────────────────┘Each CPU core has its own L1 cache (and often L2). When a thread writes a variable, the updated value may sit in the core's L1 cache for a while before being flushed to main memory. Another core's thread reading the same variable may read from its own cache — getting a stale (outdated) value.
The Visibility Problem (Without `volatile`)
1// Without volatile — BROKEN2boolean running = true; // stored in main memory3
4// Thread 1 (Core 1):5running = false; // writes to Core 1's L1 cache6 // main memory may NOT be updated yet7
8// Thread 2 (Core 2):9while (running) { // reads from Core 2's L1 cache or main memory10 // may never see running=false11 // could loop forever12}What `volatile` Does
Declaring a variable volatile makes two guarantees:
- Write guarantee: Every write to this variable goes directly to main memory, bypassing any CPU cache.
- Read guarantee: Every read of this variable comes directly from main memory, bypassing any CPU cache.
1volatile boolean running = true;2
3// Thread 1 (Core 1):4running = false; // ✅ written directly to main memory5
6// Thread 2 (Core 2):7while (running) { // ✅ always reads directly from main memory8 // will see running=false correctly9}Memory Model: Without vs With `volatile`
`volatile` Does NOT Provide Thread Safety
This is the most important distinction between volatile and AtomicInteger:
1volatile int counter = 0;2
3// Thread 1:4counter++; // STILL NOT ATOMIC — still 3 steps (LOAD, ADD, STORE)5 // volatile only ensures each individual read/write is from main memory6 // but it does NOT make the compound read-modify-write atomicvolatile solves the visibility problem. It does not solve the atomicity problem.
volatile as a substitute for synchronized or AtomicInteger when you need thread-safe mutation. volatile int counter with counter++ in multiple threads is still a race condition, even though each read/write goes to main memory.When `volatile` is the Right Tool
volatile is appropriate when:
- Only one thread writes to the variable, and other threads only read it
- You need a status/stop flag that one thread sets and others observe
- The operation on the variable is a single, inherently atomic read or write (assigning a primitive value is a single hardware instruction)
1// ✅ Correct use of volatile: one writer, many readers2public class TaskRunner {3 private volatile boolean stopRequested = false;4
5 public void requestStop() {6 stopRequested = true; // single atomic write7 }8
9 public void run() {10 while (!stopRequested) { // single atomic read11 // do work12 }13 }14}10. Atomic vs Volatile Key Differences
| Aspect | AtomicInteger (Atomic Classes) | volatile |
|---|---|---|
| Purpose | Thread-safe mutation (read-modify-update) | Ensures visibility of single reads/writes |
| Thread Safety | ✅ Yes — full thread safety for the operation | ❌ No — does not make compound ops atomic |
| Mechanism | CAS (hardware lock-free instruction) | Bypasses CPU cache; reads/writes go to main memory |
| Atomicity | ✅ Guaranteed for compound operations | Only for individual reads or writes |
| Concurrency Control | ✅ Yes | ❌ No |
| Performance | Fast for simple r-m-w (no OS lock) | Very fast (single memory fence instruction) |
| Use Case | Shared counter, shared flag with compound update | Stop flag, status variable, one-writer scenarios |
| ABA Problem | Possible; use AtomicStampedReference if needed | Not applicable |
Can replace synchronized? | For simple r-m-w operations, yes | No — never a substitute for locks |
AtomicInteger, the value field is declared volatile. This combination — volatile for visibility and CAS for atomicity — is what makes the atomic classes work correctly.11. Concurrent Collections in Java
Overview
Java provides thread-safe versions of all standard collection classes. These are found in the java.util.concurrent package and are designed for use in multi-threaded environments.
Standard Collections vs Thread-Safe Alternatives
| Standard Collection | Thread-Safe Alternative | Internal Mechanism |
|---|---|---|
ArrayList | CopyOnWriteArrayList | Copy-on-write (new array on each write) |
LinkedList | ConcurrentLinkedDeque | CAS (lock-free) |
HashMap | ConcurrentHashMap | Segmented locking / CAS (Java 8+) |
TreeMap | ConcurrentSkipListMap | CAS (lock-free skip list) |
TreeSet | ConcurrentSkipListSet | CAS (lock-free skip list) |
PriorityQueue | PriorityBlockingQueue | ReentrantLock |
ArrayDeque | LinkedBlockingDeque | Two ReentrantLocks (head/tail) |
Queue | LinkedBlockingQueue | ReentrantLock |
| — | ArrayBlockingQueue | Single ReentrantLock |
| — | SynchronousQueue | CAS (transferer mechanism) |
Vector, Hashtable, Collections.synchronizedList(...)) are legacy/wrapper solutions. The java.util.concurrent classes are preferred for modern code due to better performance and richer APIs.How Concurrent Collections Achieve Thread Safety
Different collections use different internal strategies:
`PriorityBlockingQueue` Uses `ReentrantLock`
When adding an element to a PriorityBlockingQueue, internally it acquires a ReentrantLock to ensure only one thread modifies the heap at a time:
1// Simplified internal structure of PriorityBlockingQueue.offer()2public boolean offer(E e) {3 lock.lock(); // ReentrantLock4 try {5 siftUp(n, e); // heap operation6 return true;7 } finally {8 lock.unlock();9 }10}`ConcurrentLinkedDeque` Uses CAS (Lock-Free)
The ConcurrentLinkedDeque (underlying LinkedList's concurrent alternative) uses CAS operations to link and unlink nodes without any locks:
1// Conceptual internal CAS usage in ConcurrentLinkedDeque2// When adding a node, it uses compareAndSet to atomically update pointers3node.next.compareAndSet(null, newNode); // CAS on next pointer`ConcurrentHashMap` Hybrid Approach (Java 8+)
ConcurrentHashMap uses CAS for empty bucket insertion and synchronized blocks for bucket updates with existing entries — combining both techniques for maximum performance.
Choosing the Right Concurrent Collection
12. Interview Notes
Common Interview Questions
Q1: What are the two ways to achieve concurrency in Java?
Answer: Lock-based (synchronized, ReentrantLock, Semaphore, etc.) and lock-free (atomic classes using the CAS operation).
Q2: What is CAS (Compare-And-Swap)?
Answer: CAS is a low-level, atomic CPU instruction that takes three parameters — a memory address, an expected value, and a new value. It reads the memory, compares it with the expected value, and only writes the new value if they match. This entire sequence is atomic at the hardware level.
Q3: What is the difference between `volatile` and `AtomicInteger`?
Answer:
volatileensures visibility — reads and writes go directly to main memory, so changes made by one thread are immediately visible to others. It does not provide atomicity for compound operations.AtomicIntegerprovides thread-safe atomic operations (read-modify-update) via CAS. It also usesvolatileinternally for visibility.
Q4: Is `counter++` thread-safe?
Answer: No. counter++ is three separate operations (load, increment, store). In a multi-threaded environment, threads can interleave between these steps, causing lost updates. Use AtomicInteger.incrementAndGet() or synchronized instead.
Q5: What is the ABA problem?
Answer: The ABA problem occurs in CAS-based systems when a value changes from A to B and back to A between a thread's read and its CAS attempt. Because CAS only checks the value (not the history), it incorrectly succeeds. AtomicStampedReference solves this by tracking a version alongside the value.
Q6: When should you use `AtomicInteger` over `synchronized`?
Answer: Use AtomicInteger when you have a simple read-modify-update operation on a single variable and need the best performance. Use synchronized when:
- You need to atomically update multiple variables together
- You have complex business logic in the critical section
- You need explicit locking semantics (wait/notify, etc.)
Q7: What is optimistic concurrency control? How is it related to CAS?
Answer: Optimistic concurrency control is a database-level pattern where transactions proceed without locks and check for conflicts (via a version column) at commit time. CAS is the same concept implemented in CPU hardware — check the current value against what was expected and only update if they match. OCC was inspired by the CAS hardware operation.
Q8: How does `ConcurrentHashMap` achieve thread safety?
Answer: In Java 8+, ConcurrentHashMap uses CAS for inserting into empty buckets and synchronized blocks for operations on non-empty buckets. It avoids locking the entire map, allowing much higher concurrency than Hashtable or Collections.synchronizedMap().
Q9: Why is lock-free NOT always better than lock-based?
Answer: Lock-free (CAS) works well only for simple read-modify-update on a single variable. For complex logic or coordinating multiple shared variables, CAS is insufficient — you'd need to use locks. Additionally, under very high contention, CAS loops (spinning and retrying) can consume more CPU than a lock that puts a thread to sleep.
Tricky Points to Remember
volatile≠ thread-safe. It only solves visibility, not atomicity.AtomicIntegeris internally backed by avolatile int value— it uses both concepts together.- CAS can fail and must be retried in a loop — this is called a spin loop or busy-wait.
- Atomic classes are part of
java.util.concurrent.atomic, notjava.util.concurrentdirectly. AtomicReferenceallows you to do CAS on object references, not just primitives.
13. Practice Questions
Easy
- What does
AtomicInteger.incrementAndGet()return? - How many parameters does a CAS operation take? What are they?
- What keyword ensures that reads/writes go directly to main memory?
- Is
volatilethe same assynchronized? Explain. - Name three classes in the
java.util.concurrent.atomicpackage.
Medium
- Write a thread-safe counter class using
AtomicInteger. Then rewrite it usingsynchronized. Compare the two approaches. - Explain why
counter++is not atomic even ifcounteris declaredvolatile. - Describe a scenario where using
volatileis sufficient andAtomicIntegeris unnecessary. - What happens if two threads both call
compareAndSet(0, 1)on the sameAtomicIntegersimultaneously? - Write code that uses
AtomicInteger.compareAndSet()to implement a simple spinlock.
Hard
- Implement a lock-free stack using
AtomicReferenceand CAS. - Demonstrate the ABA problem with a concrete code example and then fix it using
AtomicStampedReference. - Explain how
ConcurrentHashMapdiffers internally fromCollections.synchronizedMap(new HashMap<>()). Why doesConcurrentHashMaphave better throughput? - Design a thread-safe producer-consumer system using
LinkedBlockingQueue. Why isLinkedBlockingQueuepreferred over a manually synchronizedLinkedList? - If
AtomicIntegeruses a spin loop internally, under what conditions could it be slower thansynchronized? Describe such a scenario.
14. Summary Cheat Sheet
Key Rules to Remember
| Rule | Detail |
|---|---|
counter++ is NOT atomic | It is 3 steps: load, add, store |
volatile ≠ thread safety | Visibility only; no atomicity for compound ops |
| CAS = Compare-And-Swap | Read → Compare → Conditionally Write, all atomic |
| Atomic classes use CAS | incrementAndGet() loops until CAS succeeds |
| Lock-free ≠ always better | Works only for simple single-variable r-m-u |
| ABA problem | Value cycles A→B→A; CAS can't detect the change |
| Fix ABA | Use AtomicStampedReference with version |
| Concurrent collections | Some use locks, some use CAS — check the type |
volatile (visibility) and AtomicInteger (atomicity) is the single most
frequently confused concept in this area — master that distinction first.Mastery check
How well can you recall this?
Finished this lesson?