In Java, Collections.synchronizedCollection(c) returns a wrapper whose methods each run while holding a lock, so several threads can call add, remove, or size on it without corrupting the data.
Each single call is safe, but a sequence of calls is not automatically atomic. Iterating, or "check then add", must be wrapped in synchronized (wrapper) { ... } yourself.
A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.synchronizedCollection(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Wrap a new collection and share only the wrapper.
Java
Collection<Integer> hits = Collections.synchronizedCollection(new ArrayList<Integer>());
hits.add(1); // locked for you
synchronized (hits) { // lock manually to iterate
for (int h : hits) { /* ... */ }
}
Call
What it does
hits.add(x) / remove(x) / size()
Each call is atomic.
hits.forEach(...) / removeIf(...)
Java 8 bulk methods also lock for you.
for (x : hits) under synchronized (hits)
Iteration needs a manual lock on the wrapper.
synchronized (hits) { if (!contains) add }
Compound actions need a manual lock.
Available since Java 1.2. Like unmodifiableCollection, the wrapper does not pass equals/hashCode through to the backing collection; it uses object identity.
Library declarations
Java
// java.util.Collections
public static <T> Collection<T> synchronizedCollection(Collection<T> c)
Parameters
Parameter
Description
c
The collection to make thread-safe. Do not use it directly afterwards.
Lock-free or finer-grained structures for heavy concurrency.
Java Examples
Example 1 — Two Threads Adding at Once
Both threads add 1000 numbers to the same synchronized collection. No add is lost.
Java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class CollectionsSynchronizedCollectionThreads {
public static void main(String[] args) throws InterruptedException {
Collection<Integer> hits = Collections.synchronizedCollection(new ArrayList<Integer>());
Runnable work = () -> {
for (int i = 0; i < 1000; i++) {
hits.add(i);
}
};
Thread a = new Thread(work);
Thread b = new Thread(work);
a.start();
b.start();
a.join();
b.join();
System.out.println("size: " + hits.size() + ", contains 999? " + hits.contains(999));
}
}
Output
size: 2000, contains 999? true
How It Works
Shared target. Both threads run the same task against the one wrapper object.
Locked adds. Every add holds the wrapper's lock, so the underlying ArrayList never sees two writes at once. A plain ArrayList here could lose elements or throw.
Wait, then read.join() waits for both threads, so the count is reliably 2 × 1000 = 2000.
Example 2 — Iterate Under the Lock; forEach Locks for You
Join log lines with a for-each loop inside synchronized, then let Java 8's forEach handle the lock.