Junior — Middle
What are the main differences between CopyOnWriteArrayList and ArrayList in Java?
sobes.tech AI
Answer from AI
The main differences between CopyOnWriteArrayList and ArrayList in Java are related to thread safety and performance:
-
ArrayList is a non-thread-safe list. Concurrent access from multiple threads without external synchronization can lead to errors.
-
CopyOnWriteArrayList is a thread-safe list that implements a copying strategy on write. When the list is modified (adding, removing), a new copy of the internal array is created, allowing safe reading from multiple threads without locks.
Implications:
- CopyOnWriteArrayList is well-suited for scenarios with frequent reads and infrequent modifications.
- Due to copying on write, modification operations are slower and require more memory.
Example of using CopyOnWriteArrayList:
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("one");
list.add("two");
// Safe to read from multiple threads
for (String s : list) {
System.out.println(s);
}