Please enable JavaScript.
Coggle requires JavaScript to display documents.
5.1 Synchronized Collections - Coggle Diagram
5.1 Synchronized Collections
Definition & Mechanism
Examples: Vector, Hashtable, Collections.synchronizedXxx
Achieves thread safety by:
Encapsulating state
Synchronizing all public methods
Problems with Synchronized Collections
Thread-safe may require client-side locking for compound actions
Compound actions affected:
Iteration (fetching elements)
Navigation (finding next element)
Conditional operations (e.g., put-if-absent in a Map)
Unexpected behavior:
Concurrent modifications can lead to inconsistent states
Iterators & ConcurrentModificationException
Iterators in synchronized collections are fail-fast
They detect concurrent modifications and throw ConcurrentModificationException
How it works:
Uses a modification count
If modified during iteration, hasNext or next throws an exception
Limitations:
Not foolproof due to stale modification count
A deliberate tradeoff to reduce performance overhead
Handling Concurrent Iteration
Locking during iteration:
Prevents exceptions but blocks other threads
Can cause deadlocks or performance issues
Alternative: Cloning the Collection
Iterating a cloned version avoids modification conflicts
Tradeoff: Increased memory usage and performance cost
Hidden Iterators
Iterators can be implicitly triggered by:
toString(), hashCode(), equals()
Methods like containsAll(), removeAll(), retainAll()
Collection constructors that take other collections as arguments
Hidden iterators can still throw ConcurrentModificationException
Solution: Encapsulating synchronization to enforce policy