What are the implementations of thread-safe lists available in standard libraries or popular libraries?
sobes.tech AI
Answer from AI
In Java, the following implementations exist for thread-safe lists:
-
Collections.synchronizedList(List<T> list)— wraps a regular list in a synchronized version, where all methods are synchronized on an internal mutex. Easy to use, but requires external synchronization during iteration. -
CopyOnWriteArrayList(fromjava.util.concurrent) — a thread-safe list that creates a copy of the internal array upon modifications. Good for scenarios with many reads and infrequent modifications, as reading is not blocked. -
ConcurrentLinkedQueue— although this is a queue, not a list, it is sometimes used for thread-safe storage of elements with non-blocking access.
Example of using CopyOnWriteArrayList:
import java.util.concurrent.CopyOnWriteArrayList;
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("element1");
list.add("element2");
for (String s : list) {
System.out.println(s);
}
Thus, the choice of implementation depends on performance requirements and the nature of operations (read/write).