Java Concurrent Collections and Threading Problems: Deadlock, Starvation and Livelock (OCP 21)
Concurrent collections and threading problems for the OCP 21 exam: ConcurrentHashMap, CopyOnWriteArrayList, skip-list and blocking queue classes, synchronized wrappers, ConcurrentModificationException, then deadlock, starvation, livelock and race conditions with fixes.
kvi5hnuCode Sprout team member8 min readOn this page
The ordinary collections from Chapter 9 aren't safe to share between threads. Two threads adding to the same ArrayList or HashMap can corrupt it, throw exceptions, or quietly lose entries. The concurrent collections in java.util.concurrent are built for sharing. This article covers them, then the classic ways multithreaded programs go wrong: deadlock, starvation, livelock and race conditions.
Memory consistency and ConcurrentModificationException
A memory consistency error happens when two threads have different views of what should be the same data. The concurrent collections make sure a change made by one thread is visible to the next thread that reads the collection.
You don't even need two threads to break a regular collection. Changing a HashMap while iterating over it, except through the iterator itself, throws ConcurrentModificationException:
Map<String, Integer> stock = new HashMap<>(Map.of("violin", 2, "cello", 1, "flute", 3));
for (String key : stock.keySet())
stock.remove(key); // ConcurrentModificationException on the next iteration
Switch the map to a ConcurrentHashMap and the same loop runs without error and empties the map. Its iterators are weakly consistent: they never throw ConcurrentModificationException, and they may or may not show changes made after the iterator was created.
The concurrent collection classes
| Class | Main interfaces | Sorted? | Blocking? |
|---|---|---|---|
ConcurrentHashMap | Map, ConcurrentMap | no | no |
ConcurrentLinkedQueue | Queue | no | no |
ConcurrentLinkedDeque | Deque | no | no |
ConcurrentSkipListMap | ConcurrentMap, SortedMap, NavigableMap (and SequencedMap) | yes | no |
ConcurrentSkipListSet | SortedSet, NavigableSet (and SequencedSet) | yes | no |
CopyOnWriteArrayList | List (and SequencedCollection) | no | no |
CopyOnWriteArraySet | Set | no | no |
LinkedBlockingQueue | BlockingQueue | no | yes |
LinkedBlockingDeque | BlockingDeque | no | yes |
- Most are concurrent versions of familiar classes, so you use them through the normal interface methods, such as
get(),put(),add()andoffer(). - "Skip" means sorted.
ConcurrentSkipListMapis a concurrentTreeMap, andConcurrentSkipListSetis a concurrentTreeSet. ConcurrentHashMap, the skip lists and the linked queues don't allownullkeys, values or elements, and throwNullPointerException. The copy-on-write classes do allownull.
ConcurrentHashMap's atomic methods
Calling get() and then put() is two steps, and another thread can get in between. The ConcurrentMap methods do the whole update atomically for one key:
votes.merge("jazz", 1, Integer::sum); // count safely from many threads
usernames.putIfAbsent("NightOwl", person); // returns null only for the winner
cache.computeIfAbsent(id, this::load); // load once per key
compute, computeIfPresent, replace(key, old, new) and remove(key, value) are atomic too.
Copy-on-write collections
CopyOnWriteArrayList and CopyOnWriteArraySet copy the whole underlying array on every change. An iterator keeps using the array that existed when it was created, so it never sees later changes and never throws ConcurrentModificationException:
List<Integer> seats = new CopyOnWriteArrayList<>(List.of(10, 20, 30));
for (int s : seats)
seats.add(s + 1); // the loop still runs exactly 3 times
System.out.println(seats); // [10, 20, 30, 11, 21, 31]
Copying is expensive, so these classes suit data that's read very often and changed rarely, such as a list of event listeners. Their iterators don't support remove(), which throws UnsupportedOperationException.
Blocking queues
A BlockingQueue adds methods that wait. That makes it the standard way to pass work from producer threads to consumer threads:
| Method | When the queue is full or empty |
|---|---|
offer(e) / poll() | return false / null immediately (from Queue) |
offer(e, timeout, unit) / poll(timeout, unit) | wait up to the timeout, then return false / null. Throw InterruptedException. |
put(e) / take() | wait as long as needed. Throw InterruptedException. |
add(e) / remove() | throw an exception: IllegalStateException if full, NoSuchElementException if empty |
A LinkedBlockingQueue is unbounded unless you pass a capacity to the constructor.
Synchronized wrappers
If you're given an ordinary collection and need to share it, the Collections class can wrap it:
synchronizedCollection(c) synchronizedList(list) synchronizedSet(set)
synchronizedMap(map) synchronizedSortedMap(map) synchronizedSortedSet(set)
synchronizedNavigableMap(map) synchronizedNavigableSet(set)
Each method of the wrapper is synchronized on the wrapper object. But iterating isn't protected automatically. Modifying the collection during a for-each loop still throws ConcurrentModificationException. To iterate while other threads may modify it, hold the lock yourself:
List<String> names = Collections.synchronizedList(new ArrayList<>());
synchronized (names) {
for (String n : names) System.out.println(n);
}
When you create a collection that will be shared, prefer a concurrent class over a wrapper. Immutable collections, such as List.of(...) with immutable elements, need no synchronization at all.
Threading problems
Liveness is a program's ability to keep making progress. A liveness problem leaves threads stuck, typically BLOCKED or WAITING forever, or retrying without end.

Deadlock
Deadlock happens when two or more threads are blocked forever, each waiting for a resource another one holds. The classic cause is taking locks in opposite order:
// guitarist thread // bassist thread
synchronized (tuner) { synchronized (amp) {
synchronized (amp) { ... } synchronized (tuner) { ... }
} }
If the guitarist gets tuner and the bassist gets amp at the same moment, each waits for the other's lock forever. Both threads are BLOCKED, and if they're non-daemon threads, the program never ends.
How to prevent it:
- Lock ordering: make every thread acquire shared locks in the same order (for example, always
tuner, thenamp). With no cycle, there can be no deadlock. - Timeouts: use
tryLock(timeout, unit)(article 81). Give up and release what you hold if the second lock isn't available, then retry. - Fewer locks: hold locks briefly, and don't call unknown code while holding one.
Starvation
Starvation happens when one thread is perpetually denied access to a resource because other threads keep getting it first. The starving thread is still alive, but it never gets its turn. Unfair locks with many competing threads, or very greedy high-priority work, can cause it. A fair lock (new ReentrantLock(true)) is one remedy.
Livelock
Livelock happens when threads are active but make no progress. They keep reacting to each other, for example both releasing their lock to avoid a deadlock and then both retrying at exactly the same moment, over and over. Livelock is a special case of starvation and often comes from failed deadlock recovery. Because the threads look RUNNABLE and busy, livelock is harder to spot than deadlock. Adding a random delay before each retry breaks the symmetry.
Race conditions
A race condition is an undesirable result caused by two tasks that should run one after another running at the same time. Picture two people registering the same username at the same moment, with code that checks if (!taken(name)) create(name). Both checks can pass before either creation happens. Possible outcomes:
- Both get the account. That's the worst result, because the data is now invalid.
- Both get an error and must try again. That's annoying, but the data stays valid.
- One succeeds and the other gets an error. That's usually the best result.
Any outcome that keeps the data valid is better than one that lets invalid data in. Fix check-then-act races by making the check and the action one atomic step, for example with putIfAbsent, synchronized or a database unique constraint.
What's current
- Java 21 retrofitted sequenced collection interfaces:
ConcurrentSkipListMapis aSequencedMap,ConcurrentSkipListSetaSequencedSet, andCopyOnWriteArrayListand the concurrent deques areSequencedCollections. Hashtable,VectorandStackare old synchronized classes. They still work, but they're legacy. Prefer the concurrent classes.- The JDK can detect deadlocks for you.
jstack <pid>andThreadMXBean.findDeadlockedThreads()report threads stuck in a lock cycle. The complete example uses the latter.
Exam traps from this article
A complete example
A concert venue shares data between threads. The program shows a ConcurrentModificationException in one thread and how ConcurrentHashMap avoids it. It covers copy-on-write snapshot iteration, atomic merge counting, a username race won by exactly one putIfAbsent call, sorted skip-list collections and a bounded BlockingQueue. A synchronized wrapper still fails fast. Finally a real deadlock is detected with ThreadMXBean, and both fixes are shown: consistent lock order, and tryLock with back-off.
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
public class Solution {
/** Locks a, waits until the partner holds its first lock too, then locks b. */
static void lockBoth(Object a, Object b, CountDownLatch bothHoldOne) {
synchronized (a) {
bothHoldOne.countDown();
try { bothHoldOne.await(); } catch (InterruptedException e) { return; }
synchronized (b) {
System.out.println(" never printed");
}
}
}
/** Takes both locks with tryLock and backs off (releasing everything) if the second is busy. */
static int takeBothPolitely(Lock first, Lock second) throws InterruptedException {
int attempts = 0;
while (true) {
attempts++;
first.lock();
try {
if (second.tryLock(ThreadLocalRandom.current().nextInt(1, 10), TimeUnit.MILLISECONDS)) {
try { return attempts; } finally { second.unlock(); }
}
} finally {
first.unlock();
}
Thread.sleep(ThreadLocalRandom.current().nextInt(1, 5)); // random back-off breaks livelock
}
}
public static void main(String[] args) throws Exception {
System.out.println("== 1. Modifying while iterating, in ONE thread");
Map<String, Integer> plain = new HashMap<>(Map.of("violin", 2, "cello", 1, "flute", 3));
try {
for (String key : plain.keySet()) plain.remove(key);
} catch (ConcurrentModificationException e) {
System.out.println(" HashMap: ConcurrentModificationException");
}
Map<String, Integer> concurrent = new ConcurrentHashMap<>(Map.of("violin", 2, "cello", 1, "flute", 3));
for (String key : concurrent.keySet()) concurrent.remove(key);
System.out.println(" ConcurrentHashMap: no exception, size now " + concurrent.size());
System.out.println("\n== 2. CopyOnWriteArrayList iterates over a snapshot");
List<Integer> seats = new CopyOnWriteArrayList<>(List.of(10, 20, 30));
int loops = 0;
for (int s : seats) {
seats.add(s + 1); // changes a new copy; this loop keeps the old one
loops++;
}
System.out.println(" loop ran " + loops + " times, list is now " + seats);
try {
Iterator<Integer> it = seats.iterator();
it.next();
it.remove();
} catch (UnsupportedOperationException e) {
System.out.println(" its iterator's remove() -> UnsupportedOperationException");
}
System.out.println("\n== 3. ConcurrentHashMap: atomic per-key updates");
ConcurrentMap<String, Integer> votes = new ConcurrentHashMap<>();
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (int t = 0; t < 4; t++)
pool.execute(() -> {
for (int i = 0; i < 10_000; i++) {
votes.merge("jazz", 1, Integer::sum);
if (i % 2 == 0) votes.merge("rock", 1, Integer::sum);
}
});
}
System.out.println(" votes: " + new TreeMap<>(votes));
try {
votes.put("blues", null);
} catch (NullPointerException e) {
System.out.println(" put(key, null) -> NullPointerException (no null keys or values)");
}
System.out.println("\n== 4. Race on check-then-act, fixed with putIfAbsent");
ConcurrentMap<String, String> usernames = new ConcurrentHashMap<>();
AtomicInteger winners = new AtomicInteger();
try (ExecutorService pool = Executors.newFixedThreadPool(10)) {
for (int i = 0; i < 10; i++) {
String person = "fan" + i;
pool.execute(() -> {
if (usernames.putIfAbsent("NightOwl", person) == null) winners.incrementAndGet();
});
}
}
System.out.println(" 10 people asked for NightOwl, accounts created: " + winners.get());
System.out.println("\n== 5. Sorted concurrent collections (Skip = sorted)");
ConcurrentSkipListSet<String> bands = new ConcurrentSkipListSet<>(List.of("Owls", "Bats", "Moths"));
ConcurrentSkipListMap<Integer, String> lineup = new ConcurrentSkipListMap<>(Map.of(21, "Owls", 19, "Bats", 23, "Moths"));
System.out.println(" set: " + bands + ", first key of map: " + lineup.firstKey()
+ ", headMap(22): " + lineup.headMap(22));
System.out.println("\n== 6. BlockingQueue: offer and poll can wait");
BlockingQueue<String> orders = new LinkedBlockingQueue<>(2); // capacity 2
System.out.println(" offer x3: " + orders.offer("tea") + " " + orders.offer("cake")
+ " " + orders.offer("pie", 50, TimeUnit.MILLISECONDS));
Thread waiter = Thread.ofPlatform().start(() -> {
try {
for (int i = 0; i < 2; i++) System.out.println(" took: " + orders.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
waiter.join();
System.out.println(" poll(50 ms) on an empty queue: " + orders.poll(50, TimeUnit.MILLISECONDS));
System.out.println("\n== 7. Synchronized wrappers still fail fast when iterating");
List<String> wrapped = Collections.synchronizedList(new ArrayList<>(List.of("a", "b", "c")));
try {
for (String s : wrapped) if (s.equals("a")) wrapped.add("d");
} catch (ConcurrentModificationException e) {
System.out.println(" synchronizedList: ConcurrentModificationException");
}
synchronized (wrapped) { // iterating safely: lock the wrapper yourself
System.out.println(" iterated inside synchronized (wrapped): " + String.join("", wrapped));
}
System.out.println("\n== 8. Deadlock: opposite lock order");
Object tuner = new Object(), amp = new Object();
CountDownLatch bothHoldOne = new CountDownLatch(2);
Thread guitarist = Thread.ofPlatform().daemon(true).name("guitarist")
.start(() -> lockBoth(tuner, amp, bothHoldOne));
Thread bassist = Thread.ofPlatform().daemon(true).name("bassist")
.start(() -> lockBoth(amp, tuner, bothHoldOne));
long[] stuck = null;
for (int i = 0; i < 200 && stuck == null; i++) {
Thread.sleep(10);
stuck = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
}
System.out.println(" threads in deadlock: " + (stuck == null ? 0 : stuck.length)
+ ", states: " + guitarist.getState() + " " + bassist.getState());
System.out.println(" (they are daemon threads, so the JVM can still exit)");
System.out.println("\n== 9. Fix 1: every thread locks in the same order");
Object a = new Object(), b = new Object();
AtomicInteger finished = new AtomicInteger();
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
for (int i = 0; i < 2; i++)
pool.execute(() -> {
for (int n = 0; n < 1_000; n++)
synchronized (a) { synchronized (b) { finished.incrementAndGet(); } }
});
}
System.out.println(" 2,000 double-locks completed: " + finished.get());
System.out.println("\n== 10. Fix 2: tryLock with timeout and random back-off");
Lock mic = new ReentrantLock(), stand = new ReentrantLock();
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<Integer> singer = pool.submit(() -> takeBothPolitely(mic, stand));
Future<Integer> drummer = pool.submit(() -> takeBothPolitely(stand, mic));
System.out.println(" both finished: " + (singer.get() >= 1 && drummer.get() >= 1));
}
}
}
Output:
== 1. Modifying while iterating, in ONE thread
HashMap: ConcurrentModificationException
ConcurrentHashMap: no exception, size now 0
== 2. CopyOnWriteArrayList iterates over a snapshot
loop ran 3 times, list is now [10, 20, 30, 11, 21, 31]
its iterator's remove() -> UnsupportedOperationException
== 3. ConcurrentHashMap: atomic per-key updates
votes: {jazz=40000, rock=20000}
put(key, null) -> NullPointerException (no null keys or values)
== 4. Race on check-then-act, fixed with putIfAbsent
10 people asked for NightOwl, accounts created: 1
== 5. Sorted concurrent collections (Skip = sorted)
set: [Bats, Moths, Owls], first key of map: 19, headMap(22): {19=Bats, 21=Owls}
== 6. BlockingQueue: offer and poll can wait
offer x3: true true false
took: tea
took: cake
poll(50 ms) on an empty queue: null
== 7. Synchronized wrappers still fail fast when iterating
synchronizedList: ConcurrentModificationException
iterated inside synchronized (wrapped): abcd
== 8. Deadlock: opposite lock order
threads in deadlock: 2, states: BLOCKED BLOCKED
(they are daemon threads, so the JVM can still exit)
== 9. Fix 1: every thread locks in the same order
2,000 double-locks completed: 2000
== 10. Fix 2: tryLock with timeout and random back-off
both finished: true
Points to notice:
- The
HashMapfailed in a single thread. TheConcurrentHashMaploop removed every key without complaint. - The copy-on-write loop ran three times even though the list grew to six elements.
- Ten threads raced for the username, and exactly one
putIfAbsentreturnednull. - The third
offertimed out and returnedfalsebecause the queue's capacity was 2.pollon an empty queue returnednullafter its timeout. - The deadlocked threads were both
BLOCKED. They were created as daemon threads only so the demo could still exit. - The
tryLockversion used a random back-off, so the two threads didn't keep colliding and livelock.
Common questions
ConcurrentHashMap or Collections.synchronizedMap?
ConcurrentHashMap in almost every case. It lets many threads read and write at once, has atomic compound methods, and iterates without exceptions. The wrapper serializes every call through one lock.
Is size() exact on a concurrent collection?
Only when nothing is changing it. While other threads are updating it, size() is an estimate of a moving target.
Does a deadlock throw an exception? No. Nothing is thrown and nothing is logged. The threads just stop. That's why lock ordering and timeouts matter.
Summary
- Concurrent collections (
ConcurrentHashMap,ConcurrentLinkedQueue,ConcurrentSkipListMap/Set,CopyOnWriteArrayList/SetandLinkedBlockingQueue) are safe to share and don't throwConcurrentModificationException. - Skip-list classes are sorted, copy-on-write classes iterate over a snapshot, and blocking queues can wait in
offer,poll,putandtake. Collections.synchronizedXxx()wraps existing collections, but you must synchronize iteration yourself.- Deadlock, starvation and livelock are liveness problems. Use lock ordering, timeouts, fairness and random back-off against them.
- Race conditions lead to invalid data. Make check-then-act operations atomic.
Practice quiz
Test yourself with the concurrent collections and threading problems quiz: 10 exam-style questions with explanations.
Previous: Java Locks: ReentrantLock, tryLock, ReadWriteLock and CyclicBarrier (OCP 21)
Next: Java Parallel Streams: Parallel Decomposition, Reductions and Ordering (OCP 21)
Related reading
- Java Locks: ReentrantLock, tryLock, ReadWriteLock and CyclicBarrier (OCP 21)
- Java Thread Safety: Race Conditions, volatile, Atomic Classes and synchronized (OCP 21)
- Java ExecutorService: Runnable, Callable, Future, invokeAll and Scheduling (OCP 21)
- Java Threads: Platform and Virtual Threads, Thread States and Interrupting (OCP 21)
- Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.