Home Java Collections Methods synchronizedSet() Java Collections synchronizedSet() Method Definition In Java, Collections.synchronizedSet(s) returns a Set wrapper whose methods each run under one lock. Several threads can add and remove elements without damaging the set.
Because add returns true only when the element was new, a synchronized set gives you an atomic "claim this value" operation for free.
A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.synchronizedSet(...), after import java.util.Collections;. You never create a Collections object.
Syntax Wrap a new set and share the wrapper.
Set<String> claimed = Collections.synchronizedSet(new TreeSet<String>());
if (claimed.add(code)) {
// this thread won the code
} Call What it does set.add(x)Atomic; true for exactly one caller per new value. set.removeIf(pred)Java 8 bulk removal, locked internally. synchronized (set) { for ... }Iteration needs a manual lock. ConcurrentHashMap.newKeySet()Java 8+ concurrent alternative.
Available since Java 1.2. Iteration order is the order of the set you wrap, for example sorted for a TreeSet.
Library declarations // java.util.Collections
public static <T> Set<T> synchronizedSet(Set<T> s) Parameters Parameter Description sThe set to make thread-safe. Do not use it directly afterwards.
Return Value Return Value Description Set<T>A synchronized view of s.
Important
Loops and iterators must run inside synchronized (wrapper); otherwise a change from another thread can trigger ConcurrentModificationException. Operations spanning several calls, such as "if size < 10 then add", also need that block.
Compare with Similar Methods Related wrappers:
Java Examples 1. Concurrent union 2. Atomic claim 3. removeIf and loops Example 1 — Two Threads, Overlapping Values One thread adds 0-499 and the other 250-749. The set keeps each number once.
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
public class CollectionsSynchronizedSetUnion {
public static void main(String[] args) throws InterruptedException {
Set<Integer> seen = Collections.synchronizedSet(new TreeSet<Integer>());
Thread low = new Thread(() -> {
for (int i = 0; i < 500; i++) {
seen.add(i);
}
});
Thread high = new Thread(() -> {
for (int i = 250; i < 750; i++) {
seen.add(i);
}
});
low.start();
high.start();
low.join();
high.join();
System.out.println("size " + seen.size() + ", has 0 and 749? " + (seen.contains(0) && seen.contains(749)));
}
} size 750, has 0 and 749? true How It Works Overlap. Numbers 250-499 are added by both threads.Locked TreeSet. A bare TreeSet is not thread-safe; its tree could be corrupted by simultaneous inserts. The wrapper serializes them.Union size. 0-749 is 750 distinct numbers, and both ends are present.Example 2 — Coupon Codes Claimed Exactly Once Three shoppers race for the same 100 codes. add tells each shopper whether they got it.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class CollectionsSynchronizedSetClaim {
public static void main(String[] args) throws InterruptedException {
Set<String> claimed = Collections.synchronizedSet(new TreeSet<String>());
List<String> wins = Collections.synchronizedList(new ArrayList<String>());
Runnable shopper = () -> {
for (int i = 0; i < 100; i++) {
String code = "C" + i;
if (claimed.add(code)) {
wins.add(code);
}
}
};
List<Thread> shoppers = new ArrayList<>();
for (int s = 0; s < 3; s++) {
Thread t = new Thread(shopper);
shoppers.add(t);
t.start();
}
for (Thread t : shoppers) {
t.join();
}
System.out.println("codes claimed: " + claimed.size() + ", successful claims: " + wins.size());
}
} codes claimed: 100, successful claims: 100 How It Works Check and insert in one call. add both tests membership and inserts while holding the lock, so it needs no extra synchronized block.One winner per code. For each code, exactly one shopper sees true; the others get false.Totals agree. 300 attempts produce exactly 100 wins. Which shopper won which code varies, so only the totals are printed.Example 3 — Remove Temp Files, Then List the Rest removeIf locks internally; the reporting loop needs an explicit lock.
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
public class CollectionsSynchronizedSetCleanup {
public static void main(String[] args) {
Set<String> files = Collections.synchronizedSet(
new TreeSet<>(Arrays.asList("a.tmp", "b.txt", "c.tmp", "d.txt")));
System.out.println("before: " + files);
files.removeIf(f -> f.endsWith(".tmp"));
StringBuilder sb = new StringBuilder();
synchronized (files) {
for (String f : files) {
sb.append(f).append(' ');
}
}
System.out.println("kept: " + sb.toString().trim());
}
} before: [a.tmp, b.txt, c.tmp, d.txt]
kept: b.txt d.txt How It Works Printing is one call. toString on the wrapper takes the lock, so printing the whole set is safe.Bulk delete. removeIf scans and removes inside a single locked call, dropping both .tmp files.Your own loop. The for-each over the remaining files is wrapped in synchronized (files) so no thread can change the set mid-loop.Frequently Asked Questions What does Collections.synchronizedSet() do? It returns a Set wrapper whose methods each hold a lock, so single calls are thread-safe.
Is add() on a synchronizedSet atomic? Yes. It checks and inserts in one locked call and returns true only for the thread that actually added the element.
How do I iterate a synchronizedSet? Inside synchronized (set) { for (T x : set) ... } using the wrapper as the lock.
synchronizedSet or ConcurrentHashMap.newKeySet()? newKeySet (Java 8+) scales better under heavy concurrency and iterates without locking; synchronizedSet can wrap any set, such as a TreeSet.
Does the wrapper keep TreeSet ordering? Yes. Iteration order is whatever the wrapped set provides.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
11 people found this page helpful
Helpful Share Copy link Suggestion