Java Collections synchronizedSet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Collections

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.

Java
Set<String> claimed = Collections.synchronizedSet(new TreeSet<String>());
if (claimed.add(code)) {
    // this thread won the code
}
CallWhat 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
// java.util.Collections
public static <T> Set<T> synchronizedSet(Set<T> s)

Parameters

ParameterDescription
sThe set to make thread-safe. Do not use it directly afterwards.

Return Value

Return ValueDescription
Set<T>A synchronized view of s.

Compare with Similar Methods

Related wrappers:

MethodHow it differs
synchronizedSortedSet(s)Keeps first, last, range views.
newSetFromMap(map)With a ConcurrentHashMap, a lock-free concurrent set.
unmodifiableSet(s)Read-only set view.

Java Examples

Example 1 — Two Threads, Overlapping Values

One thread adds 0-499 and the other 250-749. The set keeps each number once.

Java
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)));
    }
}

How It Works

  1. Overlap. Numbers 250-499 are added by both threads.
  2. Locked TreeSet. A bare TreeSet is not thread-safe; its tree could be corrupted by simultaneous inserts. The wrapper serializes them.
  3. 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.

Java
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());
    }
}

How It Works

  1. Check and insert in one call. add both tests membership and inserts while holding the lock, so it needs no extra synchronized block.
  2. One winner per code. For each code, exactly one shopper sees true; the others get false.
  3. 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.

Java
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());
    }
}

How It Works

  1. Printing is one call. toString on the wrapper takes the lock, so printing the whole set is safe.
  2. Bulk delete. removeIf scans and removes inside a single locked call, dropping both .tmp files.
  3. 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

It returns a Set wrapper whose methods each hold a lock, so single calls are thread-safe.
Yes. It checks and inserts in one locked call and returns true only for the thread that actually added the element.
Inside synchronized (set) { for (T x : set) ... } using the wrapper as the lock.
newKeySet (Java 8+) scales better under heavy concurrency and iterates without locking; synchronizedSet can wrap any set, such as a TreeSet.
Yes. Iteration order is whatever the wrapped set provides.

Next: synchronizedSortedMap()

Wrap a SortedMap so each call, including range views, is thread-safe.

synchronizedSortedMap() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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