Attic
CollectionsUtilities & Concurrency

Concurrent Collections

High-throughput concurrent structures in java.util.concurrent including ConcurrentHashMap and CopyOnWriteArrayList

In multi-threaded environments, legacy synchronized collections (like Vector and Hashtable) bottleneck throughput because every operation locks the entire collection. java.util.concurrent provides thread-safe collections designed for concurrent throughput.


ConcurrentHashMap<K, V>

ConcurrentHashMap uses bucket-level intrinsic locks and atomic Compare-And-Swap (CAS) instructions to enable simultaneous reads and writes without locking the entire table.

ConcurrentHashMapDemo.java
Map<String, Integer> map = new ConcurrentHashMap<>();
map.put("active_sessions", 100);

// Atomic read-compute-write
map.compute("active_sessions", (k, v) -> v == null ? 1 : v + 1);

int count = map.get("active_sessions");

Strict Null Prohibition: ConcurrentHashMap strictly disallows both null keys and null values, throwing NullPointerException.


CopyOnWriteArrayList<E>

CopyOnWriteArrayList creates a fresh shallow clone of the underlying array whenever a mutating write (add, set, remove) is performed.

CopyOnWriteDemo.java
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("A");
list.add("B");

// Traversal uses a snapshot; no ConcurrentModificationException can occur
for (String s : list) {
    System.out.println(s);
}
  • Lock-Free Reads: Reads are exceptionally fast.
  • Fail-Safe Iterators: Iterators traverse a snapshot taken when the iterator was constructed; mutating the list during traversal does not throw ConcurrentModificationException.
  • Optimal Use Case: Read-heavy workloads with rare mutations, such as event listeners.

Legacy Structures: Hashtable

Hashtable is a legacy synchronized map dating back to Java 1.0. It disallows null keys and null values. Modern concurrent Java code should always prefer ConcurrentHashMap.

On this page