Lesson Completion
Back to course

Concurrent Collections: Thread-Safe Data Structures

Intermediate
20 minutes4.6Java

1. The Hook (The "Byte-Sized" Intro)

  • In a Nutshell: Concurrent collections (java.util.concurrent) are designed for multi-threaded access without external synchronization.
  • Key classes: ConcurrentHashMap (lock-free reads), CopyOnWriteArrayList (reads don't block writes), BlockingQueue (producer-consumer). They outperform Collections.synchronizedXxx() wrappers with better concurrency and scalability.

Think of Google Docs. Multiple people edit simultaneously (no one locks the entire document). Concurrent collections enable this for data structures!


2. Conceptual Clarity (The "Simple" Tier)

💡 The Analogy: The Shared Whiteboard

  • Synchronized Collections: One marker—take turns
  • ConcurrentHashMap: Multiple markers—divide whiteboard into sections
  • CopyOnWriteArrayList: Read from board anytime, writer makes a copy

3. Technical Mastery (The "Deep Dive")

Main Implementations

ClassUse CaseConcurrency Strategy
ConcurrentHashMapShared cache, countersSegment locking (Java 7), CAS (Java 8+)
CopyOnWriteArrayListEvent listeners, read-heavyCopy-on-write
ConcurrentLinkedQueueNon-blocking queueLock-free CAS
BlockingQueueProducer-consumerBlocking operations

Why NOT Collections.synchronizedXxx()?

  • Coarse-grained locking: Entire collection locked for each operation
  • Poor concurrency: Only 1 thread at a time
  • Iteration: Must manually synchronize

4. Interactive & Applied Code

java
import java.util.concurrent.*; import java.util.*; public class ConcurrentDemo { public static void main(String[] args) throws InterruptedException { // CONCURRENTHASHMAP: Lock-free reads Map<String, Integer> map = new ConcurrentHashMap<>(); map.put("count", 0); // NO external synchronization needed! Runnable incrementer = () -> { for (int i = 0; i < 1000; i++) { map.compute("count", (k, v) -> v + 1); // Atomic update } }; Thread t1 = new Thread(incrementer); Thread t2 = new Thread(incrementer); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Count: " + map.get("count")); // 2000 (thread-safe!) // COPYONWRITEARRAYLIST: Read-heavy scenarios List<String> list = new CopyOnWriteArrayList<>(); list.add("Item1"); // Iteration doesn't need synchronization for (String s : list) { // NO ConcurrentModificationException even if list modified! list.add("Item2"); // Creates a new copy } System.out.println("CopyOnWrite: " + list); // BLOCKINGQUEUE: Producer-Consumer BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10); // Producer new Thread(() -> { try { for (int i = 0; i < 5; i++) { queue.put(i); // Blocks if queue full System.out.println("Produced: " + i); } } catch (InterruptedException e) {} }).start(); // Consumer new Thread(() -> { try { Thread.sleep(100); // Simulate delay for (int i = 0; i < 5; i++) { int item = queue.take(); // Blocks if queue empty System.out.println("Consumed: " + item); } } catch (InterruptedException e) {} }).start(); Thread.sleep(1000); // Wait for completion } }

5. The Comparison & Decision Layer

ScenarioCollection
Read-heavy, frequent writesConcurrentHashMap
Read-heavy, rare writesCopyOnWriteArrayList
Producer-consumerBlockingQueue
Non-blocking queueConcurrentLinkedQueue

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "How does ConcurrentHashMap achieve thread-safety without locking the entire map?" Answer:

  • Java 7: Segment locking—map divided into 16 segments, each independently locked
  • Java 8+: CAS (Compare-And-Swap)—lock-free updates using atomic operations. Only locks specific nodes during writes.

Result: Multiple threads can read/write different parts simultaneously—much faster than synchronized HashMap!

Pro-Tip: When to use CopyOnWriteArrayList:

java
// ✅ GOOD: Event listeners (read 1000x, write 1x) List<EventListener> listeners = new CopyOnWriteArrayList<>(); // ❌ BAD: Frequent writes (every write copies entire list!) List<String> frequentUpdates = new CopyOnWriteArrayList<>(); for (int i = 0; i < 10000; i++) { frequentUpdates.add("item"); // 10000 array copies! }

Use CopyOnWrite only when reads >> writes!

Topics Covered

Java FundamentalsData Structures

Tags

#java#collections#list#set#map#arraylist#hashmap

Last Updated

2025-02-01