Lesson 10 / 38

Concurrent Collections

Share data safely across threads with ConcurrentHashMap, BlockingQueue for producer/consumer handoff, and CopyOnWriteArrayList for read-heavy lists.

Pick the right one

ConcurrentHashMap for shared maps (atomic compute, merge). BlockingQueue (ArrayBlockingQueue, LinkedBlockingQueue) for producer/consumer handoff. CopyOnWriteArrayList for read-heavy, rarely-written lists. Avoid Collections.synchronizedMap — it locks the whole map.

Producer/consumer with BlockingQueue

put() blocks the producer when the queue is full, take() blocks the consumer when it's empty — no manual wait/notify needed.

BlockingQueue<Job> queue = new LinkedBlockingQueue<>(100);

// producer
queue.put(job);

// consumer
Job job = queue.take();