Middle
What is the feature of using CopyOnWriteArrayList?
sobes.tech AI
Answer from AI
CopyOnWriteArrayList is a thread-safe list where modification operations (add, set, remove, etc.) create a new copy of the underlying array.
Key features:
- Thread safety: All
add,set,removeoperations are thread-safe because they do not modify the array referenced by current readers. Instead, a new array with the changes is created, and the reference is atomically updated. - Read performance: Read operations (get, iterator, etc.) are very fast because they do not require synchronization. They work with an immutable copy of the array.
- Write overhead: Write operations can be very costly, especially for large lists, because they require creating and copying the entire underlying array.
- Iterators: Iterators obtained from
CopyOnWriteArrayListare "snapshots" of the list's state at the moment of their creation. They do not reflect changes made to the list after their creation. - Usage: Suitable for scenarios with frequent reads and infrequent writes, such as lists of event listeners.
// Example of using CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArrayList;
public class COWListExample {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
// Adding an element - creates a new copy
list.add("Element 1");
// Reading elements - fast
for (String item : list) {
System.out.println(item);
}
// Snapshot iterator
// This iterator will see only "Element 1"
java.util.Iterator<String> iterator = list.iterator();
// Adding another element - creates another copy
list.add("Element 2");
// Printing elements via iterator - only "Element 1" is visible
while (iterator.hasNext()) {
System.out.println("From iterator: " + iterator.next());
}
// Printing elements from list - both elements are visible
System.out.println("From list: " + list);
}
}
Thus, CopyOnWriteArrayList is a good choice when thread safety during reading is critical and write operations are rare. Otherwise, other thread-safe collections like Collections.synchronizedList() or ConcurrentLinkedQueue might be more efficient.