Java Zero to All All questionsPractise free
Interview questions › Core & Modern Java (8 -> 21) › Collections & Equals/HashCode Contracts

When should you reach for a concurrent or copy-on-write collection instead of synchronizing a plain one?

Level III · MidCollections & Equals/HashCode Contracts
Answer

Collections.synchronizedMap wraps every method in one lock, which serializes all access and still requires manual external synchronization for compound actions and iteration, whereas ConcurrentHashMap uses fine-grained locking and lock-free reads to scale under contention and offers atomic compute and merge operations. CopyOnWriteArrayList suits read-mostly collections like listener lists where writes are rare, since each write copies the whole array. The trade-off is that copy-on-write is terrible for write-heavy workloads, and ConcurrentHashMap's iterators are weakly consistent rather than snapshot-consistent.

Common mistakes
  • Using CopyOnWriteArrayList for write-heavy lists.
  • Wrapping in synchronizedList and then iterating without a lock.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Collections & Equals/HashCode Contracts.

Practise free

More on Collections & Equals/HashCode Contracts