Reading history

Java BlockingQueue and ConcurrentHashMap: Thread-Safe Collections

6 min read 2 views

Use Java's concurrent collections: producer-consumer with BlockingQueue, poison pills, atomic updates with ConcurrentHashMap and CopyOnWriteArrayList.

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 put and take wait automatically
  • Stopping a consumer with a “poison pill”
  • Safe shared counting with ConcurrentHashMap.merge
  • When CopyOnWriteArrayList is 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’s put waits until the consumer takes one. This stops a fast producer from flooding memory; the idea is called back-pressure.
  • take waits while the queue is empty, so the consumer never spins in a busy loop wasting the processor.
  • The producer finishes by putting a special STOP object, 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. join waits 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 a ConcurrentHashMap is 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 Future with get() makes sure all jobs have finished before printing.
  • CopyOnWriteArrayList makes 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

NeedUse
Hand work from one thread to anotherArrayBlockingQueue (bounded) or LinkedBlockingQueue
Work ordered by priorityPriorityBlockingQueue
Shared map: counters, caches, lookupsConcurrentHashMap
A list of listeners, read often, changed rarelyCopyOnWriteArrayList
A single shared counterAtomicInteger or LongAdder

Common Mistakes

  1. Check-then-act on a concurrent map: if (!map.containsKey(k)) map.put(k, v) is two steps another thread can slip between. Use putIfAbsent, computeIfAbsent or merge.
  2. Using offer or poll when you meant to wait. They return immediately instead of blocking.
  3. Forgetting to stop the consumer, so the program never ends. Use a poison pill or a timeout.
  4. Using CopyOnWriteArrayList for 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

  • BlockingQueue connects producers and consumers; put and take wait for you.
  • A bounded queue gives back-pressure; a poison pill ends the consumer.
  • ConcurrentHashMap.merge and computeIfAbsent update shared maps atomically.
  • CopyOnWriteArrayList suits read-mostly lists such as listeners.

Next: Java Project: Library Management System.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *