Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
What is the difference between CopyOnWriteArrayList and a synchronized ArrayList?
| CopyOnWriteArrayList | Collections.synchronizedList(new ArrayList<>()) |
| Every mutation copies the entire underlying array. | Every method call is synchronized on a single shared lock. |
| Reads never block and never throw ConcurrentModificationException. | Reads acquire the same lock as writes, so they can be blocked by concurrent writes. |
| Iterators reflect a snapshot from when iteration started. | Iterators are fail-fast; manual synchronization is needed during iteration to avoid CME. |
| Best for read-heavy, write-rare use cases. | Best for more balanced, general-purpose read/write patterns. |
The trade-off with CopyOnWriteArrayList is cost: because every add, remove, or set copies the whole array, it becomes expensive as the list grows large or is mutated frequently, so it's specifically suited to scenarios like listener lists that are iterated far more often than they're modified.
More Related questions...