When several threads share data, ordinary collections like ArrayList and HashMap can lose updates or even break. The java.util.concurrent package provides collections built for sharing. This lesson covers the three you will use most: BlockingQueue for passing work between threads, ConcurrentHashMap for shared counters and caches, and CopyOnWriteArrayList for lists that are read far more often than they change.
In this lesson you will learn
- The producer–consumer pattern with
BlockingQueue - How
putandtakewait automatically - Stopping a consumer with a “poison pill”
- Safe shared counting with
ConcurrentHashMap.merge - When
CopyOnWriteArrayListis the right choice
You should know the basics of multithreading, including threads, thread pools and race conditions, plus HashMap.
Producer and Consumer With BlockingQueue
One thread produces work, such as incoming orders, and another consumes it. A BlockingQueue sits between them and handles all the waiting.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main {
record Order(int id, int amount) {}
static final Order STOP = new Order(-1, 0); // "poison pill" to end the consumer
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Order> queue = new ArrayBlockingQueue<>(3); // holds at most 3 orders
int[] total = {0};
int[] processed = {0};
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
queue.put(new Order(i, i * 100)); // waits if the queue is full
}
queue.put(STOP);
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = new Thread(() -> {
try {
while (true) {
Order o = queue.take(); // waits if the queue is empty
if (o == STOP) break;
total[0] += o.amount();
processed[0]++;
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("Processed " + processed[0] + " orders, total " + total[0] + " taka");
System.out.println("Queue empty at the end: " + queue.isEmpty());
}
}
Output
Processed 10 orders, total 5500 taka
Queue empty at the end: true
new ArrayBlockingQueue<>(3)holds at most 3 orders. When it is full, the producer’sputwaits until the consumer takes one. This stops a fast producer from flooding memory; the idea is called back-pressure.takewaits while the queue is empty, so the consumer never spins in a busy loop wasting the processor.- The producer finishes by putting a special
STOPobject, often called a poison pill. When the consumer takes it, it leaves the loop. The comparison uses==because it must be that exact object. - All 10 orders, 100 to 1,000 taka, are processed: 5,500 taka in total.
joinwaits for both threads and also guarantees the main thread sees their final values.
Shared Counting With ConcurrentHashMap
import java.util.*;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
List<String> lines = List.of(
"java is fun and java is fast",
"threads share memory",
"a map shared by threads must be safe",
"java threads and java maps");
// Many threads update one map; ConcurrentHashMap.merge is atomic
Map<String, Integer> safe = new ConcurrentHashMap<>();
ExecutorService pool = Executors.newFixedThreadPool(4);
List<Future<?>> jobs = new ArrayList<>();
for (int round = 0; round < 500; round++) {
for (String line : lines) {
jobs.add(pool.submit(() -> {
for (String w : line.split(" ")) {
safe.merge(w, 1, Integer::sum);
}
}));
}
}
for (Future<?> f : jobs) f.get(); // wait for every job
pool.shutdown();
System.out.println("Counts after 500 rounds (should be 500 x per-round count):");
for (String w : List.of("java", "threads", "and", "safe")) {
System.out.println(" " + w + " = " + safe.get(w));
}
// CopyOnWriteArrayList: safe to change while another loop reads it
List<String> log = new CopyOnWriteArrayList<>(List.of("start"));
for (String entry : log) log.add("seen " + entry);
System.out.println(log);
}
}
Output
Counts after 500 rounds (should be 500 x per-round count):
java = 2000
threads = 1500
and = 1000
safe = 500
[start, seen start]
- Four threads process 2,000 small jobs, each counting the words in one line. All of them update the same map at the same time.
merge(w, 1, Integer::sum)on aConcurrentHashMapis atomic: reading the old count, adding 1 and storing the result happen as one step that no other thread can interrupt. Every count is exactly 500 times its count in one round, for example “java” appears 4 times per round and ends at 2,000.- With a plain
HashMap, two threads could read the same old count and both write back old + 1, losing an update. The map can even end up corrupted. - Waiting on every
Futurewithget()makes sure all jobs have finished before printing. CopyOnWriteArrayListmakes a fresh copy of its array on every change. Loops read a snapshot, so adding during a loop is allowed. Here the loop sees only the original “start” element, so it adds exactly one entry and stops.
Choosing a Concurrent Collection
| Need | Use |
|---|---|
| Hand work from one thread to another | ArrayBlockingQueue (bounded) or LinkedBlockingQueue |
| Work ordered by priority | PriorityBlockingQueue |
| Shared map: counters, caches, lookups | ConcurrentHashMap |
| A list of listeners, read often, changed rarely | CopyOnWriteArrayList |
| A single shared counter | AtomicInteger or LongAdder |
Common Mistakes
- Check-then-act on a concurrent map:
if (!map.containsKey(k)) map.put(k, v)is two steps another thread can slip between. UseputIfAbsent,computeIfAbsentormerge. - Using
offerorpollwhen you meant to wait. They return immediately instead of blocking. - Forgetting to stop the consumer, so the program never ends. Use a poison pill or a timeout.
- Using
CopyOnWriteArrayListfor frequently changing data. Copying the whole array on every add is very slow for big lists.
Practice Exercises
Exercise 1. Change the consumer so it waits at most 2 seconds for an order and stops if none arrives.
Show answer
Order o = queue.poll(2, TimeUnit.SECONDS); // returns null after the timeout
if (o == null || o == STOP) break;
Exercise 2. Build a thread-safe cache that computes a value only the first time a key is requested.
Show answer
Map<Integer, Long> cache = new ConcurrentHashMap<>();
long result = cache.computeIfAbsent(40, n -> slowCalculation(n));
computeIfAbsent runs the calculation at most once per key, even if many threads ask at the same time. Keep the calculation short, because other updates to that key wait for it.
Frequently Asked Questions
What about Collections.synchronizedMap?
It wraps a map so that only one thread can use it at a time, which is safe but slow under heavy use. ConcurrentHashMap lets many threads read and write different parts at once, so it scales much better.
Can ConcurrentHashMap store null?
No. Neither keys nor values may be null, because a null result from get must clearly mean “no entry” when other threads may be changing the map.
Summary
BlockingQueueconnects producers and consumers;putandtakewait for you.- A bounded queue gives back-pressure; a poison pill ends the consumer.
ConcurrentHashMap.mergeandcomputeIfAbsentupdate shared maps atomically.CopyOnWriteArrayListsuits read-mostly lists such as listeners.
