Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Mastering Java Concurrent Containers: CHM Internals, CopyOnWrite, and Queue Selection

This article analyzes Java concurrent containers through three production incidents, detailing ConcurrentHashMap's CAS and fine-grained locking, CopyOnWriteArrayList's copy-on-write semantics, BlockingQueue selection guidelines, and provides migration templates and a 7-point review checklist for safe container usage.

Introduction: Why Concurrent Containers

The first five articles covered lock usage: threads and thread pools (01), synchronized (02), volatile and JMM (03), AQS and Lock (04), advanced thread pools (05). But production systems first ask: "Which container for this shared data?" Concurrent containers package previous results into ready-to-use tools: ConcurrentHashMap combines volatile (03) + CAS + synchronized bucket-level locks (02); BlockingQueue uses Condition queue transfer (04); CopyOnWriteArrayList applies immutable object safe publication (03) to the extreme. This article's stance: if a container solves it, never hand-roll locks — container authors have deeper concurrency expertise, and wrong container choice costs three real incidents.

Three Core Threads

Concurrency determines throughput: from whole-table coarse locks (Vector/synchronized wrappers) to bucket-level locks (CHM) to zero locks (COW reads, lock-free queues), finer lock granularity yields higher concurrency.

Thread-safe ≠ compound-operation-safe: CHM single operations are atomic, but containsKey+put combos still race; must use putIfAbsent/computeIfAbsent atomic APIs.

Weak consistency is a feature, not a defect: concurrent container iterators and size are weakly consistent, trading strong consistency for lock-free read performance — if you need strong consistency, add explicit locks, don't gamble on the container.

Three Production Incidents

Incident 1: Shared HashMap Causes CPU 100% Hang

A gateway service stored routing table in a plain HashMap, initialized then read by multiple threads — team thought "read-only after init is safe." During dynamic route refresh, two threads concurrently put triggered resize. JDK7 head-insertion caused two lists to point to each other forming a cycle; any get hitting that bucket looped infinitely, CPU 100% service hang. JDK8 switched to tail-insertion, cycle probability dropped sharply, but concurrent put data loss persists today . Fix: replace with ConcurrentHashMap, use computeIfAbsent for atomic refresh. Lesson: HashMap is never "safe for read-heavy" — resize and structural modifications can happen anytime — shared containers must be either fully immutable read-only or swapped for concurrent containers; no middle ground.

Incident 2: Collections.synchronizedMap Whole-Table Lock Drops Throughput 80%

A config query interface used Collections.synchronizedMap(new HashMap()) as thread-safe map. At 200 concurrency, throughput was only 20% of single-container version. Reason: synchronizedMap synchronizes every method on the same mutex object — read-read also mutually excludes: 100 threads reading same key must queue , lock contention context switches consume all throughput. Fix: switch to ConcurrentHashMap — reads fully lock-free, writes lock only single bucket head node, throughput recovered 8x. Lesson: "thread-safe" only answers yes/no, not concurrency degree — synchronized wrappers are legacy (JDK 1.2 era), their presence in modern code is a code smell.

Incident 3: CopyOnWriteArrayList Frequent Writes Trigger GC Storm

A risk system stored real-time updated rule blacklist in CopyOnWriteArrayList — ops batch-updated thousands of rules per hour, each add copying entire array (hundreds of thousands elements copied thousands of times), old gen rapidly expanded, Young GC always carried these copies, two Full GCs per day. Fix: low-frequency full replacement using volatile reference + CopyOnWriteArraySet construction (one copy per batch), high-frequency incremental updates switched to ConcurrentHashMap's Set view (newKeySet). Lesson: COW performance model is "zero-cost reads, full-cost writes" — if write frequency exceeds few per minute, or array exceeds few thousand elements, change tools.

ConcurrentHashMap Internals: CAS + Bucket-Level Locks

CHM 1.8 structure: a Node array (table), each slot a bucket — empty bucket, singly linked list (treeifies to red-black tree when length > 8 and array length ≥ 64, degradation threshold 6). Write path lock strategy in three tiers:

Empty bucket CAS direct placement — casTabAt atomically places new node into null slot, zero lock.

Non-empty bucket locks head node — synchronized(f) locks only this bucket, other buckets proceed concurrently.

Migrating bucket — head node is ForwardingNode (hash=MOVED), put assists resize then retries.

Combined effect: lock granularity = one bucket, concurrency = array length — 1.7's fixed 16 segments abandoned (memory waste + double hashing), a design-level dimensionality reduction.

Why get Is Fully Lock-Free

Three steps all volatile reads: hash locate bucket head (tabAt uses Unsafe volatile semantics), traverse list (Node val and next are volatile), red-black tree search (TreeBin search without write lock). Visibility guaranteed by Article 03 hb rule ③: put thread's volatile write to val happens-before subsequent get thread's volatile read — read always sees latest value, no locks needed. This is classic "volatile enables lock-free reads" landing: as long as structural changes don't break "read sees complete state" property (list nodes fill fields before linking), read side stays safe forever.

Two High-Frequency Pitfalls

Key/value null prohibited — get returns null cannot distinguish "absent" from "value is null" (concurrent containsKey then get two-step check inevitably races, so eliminate ambiguity at source).

Single operation atomic ≠ compound operation atomic — "if (!map.containsKey(k)) map.put(k, v)" two steps allow another thread to insert between; must use putIfAbsent/computeIfAbsent/compute/merge atomic compound APIs. One sentence: CHM locks single operations for you, compound semantics rely on APIs not if checks.

putVal Five Steps and Multi-Thread Assisted Resize

putVal complete flow five steps:

Locate — spread(hash) perturbation (high 16 bits XOR low 16 bits, letting high bits participate in bucket selection), (n-1) & hash determines bucket.

Empty bucket CAS — casTabAt direct placement, success ends.

Check head node — hash==MOVED means bucket migrating, helpTransfer assists moving bucket then retries own put.

synchronized(f) locks head node — traverse list/tree insert or overwrite (onlyIfAbsent semantics = putIfAbsent), inside lock re-checks if head node replaced.

addCount — element count increment, incidentally checks resize trigger.

Two steps CAS, one step bucket lock, one step assist — these four "yield mutual exclusion" attempts are the entire source of CHM high concurrency.

Resize (transfer) Is CHM's Most Ingenious Part

Trigger — addCount finds element count exceeds sizeCtl threshold, initiates resize, capacity doubles.

Division of labor — by stride (min 16) divides bucket ranges into segments, each participating thread claims one segment to migrate independently, multi-thread parallel moving.

Marking — when a bucket finishes migrating, original array slot gets ForwardingNode (points to new array), get hitting it goes to new array to read, put hitting it assists first.

Assistance — any write thread hitting ForwardingNode helps move a segment then continues own operation — resize cost amortized across all concurrent write threads, not one unlucky thread moving everything .

Contrast HashMap single-thread resize (millions of buckets, one put may stall hundreds of milliseconds), CHM smooths this spike away.

Why size Is an "Approximate Value"

Counting uses CAS accumulation: no contention adds to baseCount; once CAS fails (high contention), switches to CounterCell array scattered accumulation (LongAdder same idea, Article 07 details), sumCount sums baseCount + all cells. Concurrent modifications during traversal don't freeze, size is just a "roughly matches" number — monitoring OK, accounting reconciliation not OK (need external lock or evaluate ConcurrentLinkedQueue.size doc semantics yourself).

CopyOnWrite and BlockingQueue: Two Other Personalities

CopyOnWriteArrayList Model

Read = direct read volatile array reference, zero lock zero wait

Write = lock + Arrays.copyOf copy new array + modify + setArray swap reference — write threads mutually exclusive (ReentrantLock), readers always read "some complete version". Its iterator is snapshot at creation time: modifications during traversal by other threads don't affect this traversal, no ConcurrentModificationException — this is immutable object safe publication (Article 03) taken to the extreme: each write publishes a new immutable array . Applicable scenarios therefore extremely narrow: reads far exceed writes (listener lists, routing tables, black/white lists), array not large, can tolerate reading slightly stale version. Incident 3's GC storm was using this narrow scenario broadly.

BlockingQueue Four API Groups by "Full/Empty Behavior"

add/remove/element — full/empty throw exceptions (probe type, testing use).

offer/poll/peek — full/empty return false/null (probe without blocking, suitable for submissions with fallback paths).

put/take — full/empty block waiting (producer-consumer main use, natural backpressure).

offer(e,t)/poll(t) — timed blocking (interruptible fallback, Article 05 tryLock timeout queue version).

Implementation selection:

ArrayBlockingQueue fixed capacity, memory controllable, production default.

LinkedBlockingQueue default near-unbounded (must explicitly give capacity).

SynchronousQueue zero capacity direct handoff (Article 05 covered).

DelayQueue delayed dequeue (scheduled tasks).

PriorityBlockingQueue priority (task grading).

Two More Tiers

ConcurrentLinkedQueue/Deque — Michael-Scott lock-free queue (CAS enqueue/dequeue), non-blocking: full never blocks (unbounded, trades memory for throughput), suitable for high-throughput low-contention producer-consumer not needing backpressure.

ConcurrentSkipListMap/Set — skip list implementation, concurrent and ordered (range queries firstKey/tailMap), TreeMap's concurrent replacement — when you need "concurrent + sorted" it's almost the only choice (CHM unordered, locked TreeMap throughput poor). Note lock-free containers iterators are weakly consistent, and most lock-free containers size is O(n) traversal (no count maintained), don't repeatedly call on hot paths.

Concurrent Container Capability Cross-Reference (One Table)

CHM — hash KV, high-concurrency read/write, weak consistency, null forbidden.

COW List/Set — reads extremely fast, writes extremely slow, snapshot iteration.

BlockingQueue — blocking conveyor belt, producer-consumer standard, select API by full/empty behavior.

ConcurrentLinkedQueue — lock-free unbounded, no backpressure.

SkipListMap — concurrent ordered range queries.

Selection three questions: read/write ratio (decides CHM vs COW)? Need blocking semantics (decides Queue family)? Need ordering (decides SkipList)? Three answers directly point to container.

Production Practice: Three Scenarios Three Templates

5.1 Local Cache: CHM + computeIfAbsent (Incident 1/2 Fix)

private final Map<String, Config>
cache = new ConcurrentHashMap<>();

public Config get(String key) {
// Atomic: compute only if absent
return cache.computeIfAbsent(
key, k -> loadFromDb(k));
}

public void refresh(String key) {
// Atomic replace, no get+put race
cache.compute(key,
(k, v) -> loadFromDb(k));
}

Standard fix for incidents 1/2, three key points:

computeIfAbsent is atomic — concurrent loads for same key only one thread actually executes loadFromDb, others block waiting for result, naturally prevents cache stampede.

compute for refresh — replaces containsKey+put race window.

Cleanup expired using entrySet().removeIf — weakly consistent traversal cleanup is "best effort", backed by scheduled task. Two constraints: computeIfAbsent mapper must not update same map (possible deadlock/IllegalStateException); high-cost loading needs timeout control in mapper, else one slow query blocks all threads waiting for same key. For full-featured TTL cache directly use Caffeine — CHM cache is "lightweight" solution, don't hand-roll eviction algorithms on top.

5.2 Blacklist/Listeners: COW Snapshot (Incident 3 Correct Usage)

private volatile Set<String> blacklist =
new CopyOnWriteArraySet<>();

public boolean hit(String uid) {
// Read: every request checks, zero lock
return blacklist.contains(uid);
}

// Background low-frequency full replacement (Incident 3 fix)
public void reload(List<String> ids) {
blacklist =
new CopyOnWriteArraySet<>(ids);
}

This is Incident 3's correct form:

Hot path only reads (per-request contains),

Writes converged to background low-frequency full replacement (ops finishes name list, one-time reload, one copy per batch not per-item add). COW criteria written into review checklist: write frequency below few per minute, array elements within few thousand, reads tolerate millisecond-level staleness — all three must hold to allow COW . Listener lists are another COW standard scenario: register/unregister low-frequency config behavior, event trigger traversal high-frequency, snapshot iteration also guarantees listener list stability during callbacks. High-frequency incremental blacklist updates correct tool is ConcurrentHashMap.newKeySet() — it has CHM concurrency and writes don't copy .

5.3 Producer-Consumer: BlockingQueue Standard Posture (Article 05 Continued)

private final BlockingQueue<Task> queue =
new ArrayBlockingQueue<>(1000);

public void submit(Task t)
throws InterruptedException {
// Full blocks: natural backpressure
queue.put(t);
}

// Consumer thread main body
public void run() {
while (running) {
Task t = queue.take(); // Empty blocks
try {
handle(t);
} catch (Exception e) {
log.warn("task fail", e);
}
}
}

Combined with Article 05 thread pool knowledge: ArrayBlockingQueue(1000) + put/take is "manual thread pool" skeleton — put full blocks giving upstream natural backpressure (gentler CallerRunsPolicy), take empty blocks not burning CPU, graceful shutdown uses offer(e, 2, SECONDS) timed submit + poll(5, SECONDS) timed consume drain. When to hand-roll BlockingQueue instead of thread pool: need consumer batch pull (drainTo grab N at once), need tasks deduplicated/merged in queue, or consumer rate needs fine control — these thread pool queues can't do. Four API groups selection discipline: main path put/take (complete backpressure), submitter needs fallback use offer timeout version, add/elem group only appears in tests .

5.4 Legacy Code Replacement: Synchronized Wrapper Migration Checklist

// Anti-pattern: synchronized wrapper, whole-table coarse lock
Map<String, User> m =
Collections.synchronizedMap(
new HashMap<>());
// Anti-pattern: HashMap + manual lock
synchronized (rawMap) {
if (!rawMap.containsKey(k))
rawMap.put(k, v);
}

// Correct: CHM atomic compound operation
ConcurrentMap<String, User> m2 =
new ConcurrentHashMap<>();
m2.computeIfAbsent(k,
x -> loadUser(x));

Migration checklist by benefit order:

synchronizedMap/Hashtable → CHM : read throughput from serial back to lock-free, biggest win.

Vector → CopyOnWriteArrayList or ArrayList+external lock : depends on read/write ratio.

Manual lock + if/put → putIfAbsent/compute : race window disappears with lock.

synchronizedList iteration blocks → COW snapshot .

Migration checkpoint only one: semantics equivalent after replacement? — synchronized wrapper is strong consistency iteration, CHM is weak consistency, code relying on strong consistency (e.g., precise accounting traversal) must explicitly add lock protection. Incidentally add HashMap concurrent usage detection to review: grep shared HashMap, ask "multi-threaded?", one-vote veto.

Concurrent Container Review 7-Point Physical (One-Vote Veto)

Still sharing HashMap/ArrayList across threads? (Incident 1)

Still using Collections.synchronizedXxx/Vector/Hashtable? (Incident 2)

containsKey+put/get+judge compound operations replaced with atomic APIs?

Code depends on null semantics? (CHM forbids null, get null-check logic must review)

Using size/iteration as strong consistency? (Accounting logic must external lock)

Blocking semantics chosen correctly? (Main path put/take, fallback offer timeout, test add)

COW write frequency and array size exceed criteria? (Incident 3)

All seven pass, container considered safe for duty.

Core Source Code: Four Key Implementations

First Segment: putVal Core Five Steps

Original form of three-tier lock strategy:

// CHM.putVal (JDK 17 simplified)
final V putVal(K key, V value,
boolean onlyIfAbsent) {
int hash = spread(key.hashCode());
for (Node<K,V>[] tab = table;;) {
if (tab == null)
tab = initTable();
else if ((f = tabAt(tab, i))
== null) {
// Empty bucket: CAS direct place
if (casTabAt(tab, i, null,
newNode(hash, key, value,
null)))
break;
}
else if (f.hash == MOVED)
// Bucket migrating: assist then retry
tab = helpTransfer(tab, f);
else {
// Non-empty bucket: lock head node
synchronized (f) {
// Traverse list/tree insert,
// onlyIfAbsent semantics
}
break;
}
}
addCount(1L, 0); // Count + resize check
return null;
}

Reading this source code grasp three structures:

for(;;) infinite loop + branches break/continue — CAS or assist failure loops back to head retry, isomorphic to Article 04 AQS spin.

tabAt/casTabAt/setTabAt — Unsafe volatile read/CAS/volatile write, array element atomic access trio (volatile array elements don't guarantee atomic access, must use Unsafe/VarHandle).

synchronized(f) locks head node object itself — no extra lock field, lock granularity naturally equals bucket, and head node replacement (resize/treeify) re-validates inside lock.

Empty bucket CAS no lock, non-empty bucket lock head, migrating bucket assist first — three-tier strategy expressed clearly in one loop.

Second Segment: ForwardingNode and Assisted Resize

transfer scheduling core:

// ForwardingNode: hash=MOVED(-1)
// Marker node holding nextTable reference
static final class ForwardingNode
extends Node<K,V> {
Node<K,V>[] nextTable;
Node find(int h, Object k) {
// Get hits F node:
// Directly search new array
Node<K,V>[] nt;
if ((nt = nextTable) != null)
return searchInTable(nt, h, k);
return null;
}
}

// helpTransfer: put hits F node
final Node<K,V>[] helpTransfer(
Node<K,V>[] tab, Node<K,V> f) {
ForwardingNode fw = (ForwardingNode) f;
// Validate new array then participate migration:
transfer(tab, fw.nextTable);
// transfer internally claims bucket segments by stride,
// migrated buckets backfill ForwardingNode
return fw.nextTable;
}

ForwardingNode is consistency pivot during resize:

It exists simultaneously in both old and new array worlds — old array slot's F node tells all visitors "this bucket moved to nextTable", get via its find goes straight to new array, put via helpTransfer participates in moving.

Why get needs no lock yet loses no data: migration copies bucket nodes one by one "deep copy" to new array (new nodes keep val reference unchanged), F node placed after old bucket becomes unwritable, reads either see pre-migration state in old bucket or via F node see post-migration state in new bucket — both states complete , exactly "immutable intermediate state" pattern. Transfer's stride segmentation and sizeCtl high-bit marking (records participating thread count) details numerous, master "segment + mark + assist" three keywords covers interviews and troubleshooting.

Third Segment: addCount and CounterCell

Scattered counting idea:

// addCount (JDK 17 minimal)
private final void addCount(long x,
int check) {
CounterCell[] as; long b, s;
// Try CAS baseCount
if (as == null || !casBaseCount(
b = baseCount, s = b + x)) {
// baseCount contention failed:
// Scatter to CounterCell array
int i = ThreadLocalRandom
.current()
.nextZeroCellIndex();
if (cellsBusy == 0
&& casCell(i, 0L, x))
return;
fullAddCount(x, ...); // Fallback spin
return;
}
// check >= 0 checks resize condition
if (check >= 0) {
// Element count >= sizeCtl -> transfer
}
}

Counting difficulty: if size just a long field, million QPS all write threads CAS same variable, contention failure rate extreme. CounterCell solution turns "one hot variable" into "group of cold variables": thread CAS baseCount fails switches to cell array random position accumulate, statistics sum them — this is LongAdder core idea (Article 07 protagonist), CHM just used it first. Thread locates cell using ThreadLocalRandom probe (threadLocalRandomProbe) ensuring same thread mostly hits same cell (cache friendly). Resize check embedded after counting success: only write ops with check >= 0 trigger check, bucket-lock updates don't trigger — sizeCtl is "threshold + state + thread count" three-in-one field, reading it requires sc mask logic.

Fourth Segment: CopyOnWriteArrayList add and get

Shortest source code:

// COW (JDK 17 simplified)
final transient Object lock =
new ReentrantLock();
private transient volatile
Object[] array;

final Object[] getArray() {
return array; // volatile read
}

public boolean add(E e) {
synchronized (lock) {
Object[] es = getArray();
int len = es.length;
// Copy new array +1
es = Arrays.copyOf(es, len + 1);
es[len] = e;
setArray(es); // volatile reference replace
return true;
}
}

public E get(int index) {
// Zero lock: snapshot array direct read
return elementAt(getArray(), index);
}

Ten-odd lines condense Article 03 "immutable object safe publication" entirely:

Array content immutable (each write produces new array, old array forever complete);

Volatile reference publication — setArray write happens-before subsequent getArray read, reader seeing new reference necessarily sees complete array (final field semantics backstop);

Read zero-lock, write mutually exclusive — lock only protects write-write concurrency.

This directly yields its two boundaries: write cost O(n) (copy), memory doubles (old and new arrays coexist) — Incident 3's GC storm is the price of these two boundaries. Understanding this segment, ImmutableList + volatile reference hand-rolled pattern also becomes trivial.

Seven Accounts: Concurrent Container Selection and Replacement

First Account: HashMap Concurrency Account

Incident 1's infinite loop + fix cost comparison stark — switch to CHM is one-line change, CPU 100% production incident is downtime loss ; spec "shared container must be concurrent container" one-vote veto is this account solidified.

Second Account: Lock Granularity Account

Synchronized wrapper whole-table lock throughput 20% vs CHM bucket lock 8x recovery — lock granularity from container-level to bucket-level benefit is orders of magnitude; conversely, read fully lock-free (COW/CHM get) benefit is another bucket-lock multiple . Choosing container essence is choosing lock granularity.

Third Account: COW Cost Account

COW write cost O(n) + memory double not bug but design — it pushes "read performance" to extreme while pushing "write cost" to extreme, only profitable when read/write ratio extreme (>1000:1) ; Incident 3's GC storm is out-of-bounds usage direct bill.

Fourth Account: Weak Consistency Account

Weak consistency iteration and approximate size buy lock-free reads — account both sides: monitoring, cache, routing "close enough" scenarios free win; accounting, audit, precise stats scenarios must external lock, don't use wrong ledger .

Fifth Account: Compound Operation Account

containsKey+put race window appears occasionally in stress test, inevitably in production — atomic APIs (putIfAbsent/computeIfAbsent/compute/merge) not only eliminate races but also eliminate null-check boilerplate ; this account yields correctness and readability double win.

Sixth Account: Resize Smoothing Account

HashMap single-thread resize hundred-millisecond spikes vs CHM assisted resize distributes moving to write threads — this account shows in capacity planning as P99 stability: spike-free containers make capacity estimation more accurate ; large-capacity hash containers prefer CHM not preference but accounting.

Seventh Account: Ecosystem Account

CHM bucket lock is Article 02 synchronized textbook application, CounterCell is Article 07 LongAdder preview, F node assist is "immutable intermediate state" design pattern, COW is immutable publication extreme — this article is first large-scale merge of first five articles' knowledge, reading source code process strings previous five into a network . Seven accounts summary: concurrent container selection discipline (three questions + seven-point physical) dev cost is "each spot review ten seconds", corresponding benefit is direct prevention of three incidents — this is the highest "API swap avoids accidents" concentration article in the series .

20 Interview Questions (With Answers)

The article includes 20 detailed Q&A covering HashMap concurrency issues, CHM 1.7 vs 1.8 differences, putVal flow, lock-free get, null prohibition, size counting, resize assistance, ForwardingNode, compound operation safety, computeIfAbsent usage, weak consistency iterator, CHM vs synchronizedMap, COW principles and scenarios, COW iterator traits, COW lock-free read safety, BlockingQueue four API groups, ArrayBlockingQueue vs LinkedBlockingQueue selection, SynchronousQueue characteristics, ConcurrentLinkedQueue traits and limits, and concurrent container selection methodology. Each answer is concise and technically precise, referencing the article's core concepts.

One-Page Cheat Sheet

Three summary boxes covering CHM internals (array+list/tree thresholds 8/6; empty bucket CAS, non-empty bucket synchronized head, migrating bucket F node assist; get all volatile reads lock-free via hb rule ③; null forbidden; putIfAbsent/computeIfAbsent for compound ops; size=baseCount+CounterCell sum approximate; resize stride multi-thread assist, F node pivot), COW and queues (COW=immutable array+volatile publish: read zero-lock, write lock+copyOf+setArray, iterator snapshot; criteria: write below few per minute and array within few thousand; BlockingQueue four APIs: add throw/offer false/put block backpressure/offer timeout fallback; Array fixed capacity default, Linked explicit capacity, Synchronous zero buffer handoff, Delay delayed, Priority priority), Selection and physical (Selection three questions: read/write ratio? blocking? ordered? — directly maps CHM/COW/Queue/SkipList; Red line: multi-thread shared HashMap must replace; Seven-point physical: shared HashMap, synchronized wrapper, compound ops API, null dependency, size as strong consistency, blocking semantics, COW write frequency exceed; Weak consistency is feature not defect, accounting must external lock).

This article packs first five articles' knowledge into containers: CHM's three-tier lock strategy (CAS/bucket lock/assist resize) is synchronized and CAS merger, get lock-free is volatile semantics direct delivery, COW is immutable publication extreme, BlockingQueue is Condition queue transfer productized. Selection discipline only three questions plus one red line: read/write ratio, blocking semantics, ordering needs, plus "shared ordinary collections must replace" — answer these three questions, container has already locked for you .

Next article "CAS and Atomic Classes" covers concurrency world's "optimists": CAS appearing repeatedly here formally debuts — Unsafe.compareAndSwapInt hardware atomic instruction (x86 lock cmpxchg), AtomicLong and LongAdder segmented counting (CHM CounterCell origin), ABA problem and AtomicStampedReference solution, atomic references and field updaters, and "optimistic spin vs pessimistic block" selection checklist.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

performance optimizationThread SafetyConcurrentHashMapCopy-on-WriteJava concurrencyBlockingQueueCopyOnWriteArrayListFine-Grained Locking

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion