Junior — Middle
Explain the working principle and features of CopyOnWriteArrayList in Java
sobes.tech AI
Answer from AI
CopyOnWriteArrayList is a thread-safe implementation of the List interface in Java that uses a copy-on-write strategy.
Working principle:
- Each modification operation (add, remove, update) creates a new copy of the internal array.
- Reading occurs without locks, directly from the current array.
Features:
- Ideal for scenarios with frequent reads and infrequent modifications.
- High read performance due to the absence of locks.
- Modifications are costly because of copying the entire array.
- Iterators do not throw ConcurrentModificationException and always work with an immutable copy of the data at the time of creation.
Example usage:
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("A");
list.add("B");
for (String s : list) {
System.out.println(s);
}
list.add("C"); // will create a new copy of the array
This list is convenient, for example, for storing event subscribers, where adding/removing occurs rarely, but notifications are frequent.