In Java, Collections.synchronizedList(list) returns a List wrapper in which every method, including index-based ones like get(i) and set(i, x), holds a lock while it runs.
The usual idiom is Collections.synchronizedList(new ArrayList<>()): create the list inside the call, so the only reference anyone has is the safe wrapper.
A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.synchronizedList(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Create and wrap in one expression.
Java
List<Integer> ids = Collections.synchronizedList(new ArrayList<Integer>());
ids.add(7); // thread-safe
synchronized (ids) { // required for iteration
for (int id : ids) { /* ... */ }
}
Call
What it does
ids.add(x) / get(i) / set(i, x)
Each call is atomic.
ids.sort(cmp) / replaceAll(op)
Java 8 bulk methods lock for you.
synchronized (ids) { new ArrayList<>(ids) }
A consistent snapshot.
synchronized (ids) { for ... }
Iteration must be manually locked.
Available since Java 1.2. If the original list implements RandomAccess (like ArrayList), the wrapper does too. For lists that are read far more often than written, CopyOnWriteArrayList from java.util.concurrent is an alternative.
Library declarations
Java
// java.util.Collections
public static <T> List<T> synchronizedList(List<T> list)
Parameters
Parameter
Description
list
The list to make thread-safe. Do not keep using it directly.
Type-checked list; can be combined with this wrapper.
Java Examples
Example 1 — Four Threads Filling One List
Each thread adds its own block of 250 IDs. Afterwards, sort and check the ends.
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsSynchronizedListWorkers {
public static void main(String[] args) throws InterruptedException {
List<Integer> ids = Collections.synchronizedList(new ArrayList<Integer>());
List<Thread> workers = new ArrayList<>();
for (int t = 0; t < 4; t++) {
final int start = t * 250;
Thread th = new Thread(() -> {
for (int i = start; i < start + 250; i++) {
ids.add(i);
}
});
workers.add(th);
th.start();
}
for (Thread th : workers) {
th.join();
}
Collections.sort(ids);
System.out.println("size " + ids.size() + ", first " + ids.get(0) + ", last " + ids.get(ids.size() - 1));
}
}
Output
size 1000, first 0, last 999
How It Works
Separate ranges. Thread 0 adds 0-249, thread 1 adds 250-499, and so on, all into the same wrapper.
Arrival order varies. The threads interleave, so the list is unsorted after joining. Collections.sort calls the wrapper's sort, which locks internally.
Nothing lost. All 1000 IDs are present, from 0 to 999.
Example 2 — Take a Snapshot Under the Lock
Copy a chat history while holding the lock, then keep using the copy without blocking other threads.