CKTIS / Java
Collections.synchronizedList — a synchronized list wrapper
Collections.synchronizedList adds synchronization to a list. Traversal and sequences of dependent operations require additional locking.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public static <T> List<T> synchronizedList(List<T> list)Collections.synchronizedList(list) returns a synchronized view backed by list, not a copy. T denotes the element type. This wrapper adds synchronization; it does not make the list unmodifiable.
All access to the backing list should go through the returned wrapper. Synchronizing individual calls does not make a contains followed by add atomic; enclose both calls in synchronized (names).
Traversal through Iterator, Spliterator, or Stream requires locking the returned list throughout traversal. This also applies to enhanced for loops; create the iterator inside the block. Omitting the lock can produce nondeterministic behavior.
Examples
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = Collections.synchronizedList(new ArrayList<>());
names.add("Ada");
synchronized (names) {
if (!names.contains("Lin")) {
names.add("Lin");
}
for (String name : names) {
System.out.println(name);
}
}
}
}Result
Ada Lin
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.