When multiple threads access a collection at the same time, you ned thread-safe data structure to avoid:

  • race conditions,
  • ConcurrentModificationException,
  • corrupted data.

Synchronized Collections (Legacy)

These are wrapper methods from Collections utility class.

List<String> syncList = Collections.synchronizedList(new ArrayList<>());
FeatureBehavior
Thread-safe?βœ… Yes (synchronized blocks)
Performanceβœ— Slower (global locking)
Fail-safe Iteratorβœ— No (ConcurrentModificationException)

Synchronized wrappers use coarse-grained locking - one thread at a time.

Concurrent Collections (Modern)

These are built-in thread-safe classes from java.util.concurrent.

Collection TypeClass NameNotes
MapConcurrentHashMapNo locking entire map, segment-based
ListCopyOnWriteArrayListCopy-on-write on mutation (read-heavy use)
SetCopyOnWriteArraySetSame idea, based on CopyOnWriteArrayList
QueueConcurrentLinkedQueueNon-blocking, lock-free queue

Example

ConcurrentHashMap
Map<String, Integer> map = new ConcurrentHashMap<>();
map.put("A", 1);
map.put("B", 2);

Use Case

SituationUse This
Multi-threaded legacy codeCollections.synchronizedX
High-performance appsConcurrentHashMap, etc.
Read-heavy, write-rareCopyOnWriteArrayList
Blocking queuesArrayBlockingQueue, etc.

Tip

Be ready to:

  • explain why regular ArrayList/HashMap isn’t thread-safe,
  • compare synchronizedList() vs CopyOnWriteArrayList,
  • know that iterating over synchronized collections still need external synchronization.

Parent: _Collections