Is HashSet thread-safe, and how do you safely share a set of unique elements across multiple threads?
answer
- HashSet/LinkedHashSet are NOT thread-safe
- Fail-fast iterator throws ConcurrentModificationException
- synchronizedSet = one lock; still lock manually to iterate
- ConcurrentHashMap.newKeySet() for high write concurrency (weakly-consistent iterators)
- Set.copyOf/Set.of = unmodifiable, no locks needed
basics
~10 sNo, HashSet is not thread-safe. With even one writer, readers can get errors or miss elements, and concurrent writers can corrupt it. Use a concurrent set or external synchronization to share one safely.
solid answer
~50 sHashSet (and LinkedHashSet) are not thread-safe: if threads access one concurrently and at least one modifies it, you must synchronize externally. Uncoordinated access can corrupt the internal structure, lose updates, or, during iteration, throw ConcurrentModificationException via the fail-fast iterator. For shared mutable access you have options. Collections.synchronizedSet(new HashSet<>()) wraps each ordinary method call in a single lock — simple but a bottleneck, and you must still manually synchronize on the set while iterating. For high concurrency prefer ConcurrentHashMap.newKeySet(), a concurrent set built on CAS and per-bin locks, with weakly-consistent iterators that never throw CME. If the set is built once and only read afterwards, make it unmodifiable with Set.copyOf or Set.of so the set needs no synchronization; neither accepts null. If the set is small and writes are rare versus reads, a CopyOnWriteArraySet can fit, though its contains is a linear scan. The right choice depends on the read/write ratio and contention.
code
java · 13 lines// NOT safe under concurrent writes:
Set<String> unsafe = new HashSet<>();
// Option A: coarse lock; remember to sync around iteration too
Set<String> sync = Collections.synchronizedSet(new HashSet<>());
synchronized (sync) { for (String s : sync) { /* ... */ } }
// Option B: concurrent set, weakly-consistent iterator, no CME
Set<String> concurrent = ConcurrentHashMap.newKeySet();
concurrent.add("x"); // many threads can do this concurrently
// Option C: unmodifiable copy, needs no locks (read-only)
Set<String> unmodifiable = Set.copyOf(unsafe);go deeper
Knows HashSet is not thread-safe and that a concurrent or synchronized alternative is needed for shared writes.
Lists the safe options (synchronizedSet, ConcurrentHashMap.newKeySet, unmodifiable) and knows the fail-fast iterator throws CME.
Chooses among options by read/write ratio and contention, explains weakly-consistent vs fail-fast iterators, and the compound-action atomicity gap.
Designs concurrency strategy across a system (immutability by default, concurrent sets where needed), reasons about throughput/contention trade-offs and resize-corruption hazards.
## What 'thread-safe' means A class is **thread-safe** if multiple threads can use the same instance concurrently without external locking and still behave correctly. **HashSet is not thread-safe.** Neither is LinkedHashSet. Their Javadoc requires external synchronization whenever threads access one concurrently and at least one of them modifies it, so one writer with concurrent readers is already unsafe. ## What goes wrong without coordination If two threads `add`/`remove` on the same HashSet at the same time: - **Lost updates**: one thread's change overwrites another's. - **Structural corruption**: a concurrent resize/rehash can leave the bucket array in a broken state, so elements go missing and `size()` can disagree with what iteration returns. - **ConcurrentModificationException (CME)**: HashSet's iterator is **fail-fast** — it keeps a `modCount` and throws CME if the set changes structurally during iteration (even from the same thread, e.g. removing inside a for-each without the iterator's own `remove`). This is a *best-effort* bug detector, not a guarantee. ## The safe options, from simplest to most concurrent **1. Unmodifiable (read-only after build) — best when possible.** If you populate the set once and only read it afterwards, copy it so nobody can mutate it: `Set.copyOf(original)` (Java 10+), or build it with `Set.of(a, b, c)` (Java 9+). No locks needed and no resize races, though a mutable element can still change. Both reject `null`, which `HashSet` permits, and `Set.of` throws on duplicates. **2. `Collections.synchronizedSet(new HashSet<>())`.** Returns a wrapper that guards each ordinary method call with one intrinsic lock. Correct but coarse: those calls serialise through a single lock (a bottleneck under contention). Caveat: **iteration is not automatically safe** — you must manually `synchronized (set) { for (... ) ... }` around the loop, or you can still get CME. **3. `ConcurrentHashMap.newKeySet()` (Java 8+) — the modern default for a concurrent mutable set.** This is a Set view backed by ConcurrentHashMap, which rejects `null`. It uses fine-grained locking/CAS so many threads can write to different buckets simultaneously. Its iterators are **weakly consistent**: they reflect the set's state at some point at or since their creation, never throw CME, and tolerate concurrent modification. Allows high throughput. **4. `CopyOnWriteArraySet` — for read-heavy, write-rare sets.** Adding or removing an element usually copies the whole backing array. Reads and iteration are lock-free and never throw CME, but those writes are O(n) and expensive, and `contains` is a linear `equals` scan, also O(n), because there is no hash table. Good for small sets read far more than written (e.g. listener lists). ## Choosing | Situation | Choice | |---|---| | Built once, then read-only | `Set.copyOf` / `Set.of` (unmodifiable) | | Low contention, simplicity | `Collections.synchronizedSet` | | High write concurrency | `ConcurrentHashMap.newKeySet()` | | Small set, many reads, rare writes (`contains` is a linear scan) | `CopyOnWriteArraySet` | ## Key reminder Wrapping with `synchronizedSet` does **not** make compound actions atomic (e.g. check-then-add). For those you still need to hold the lock across the whole compound operation, or use a concurrent set's atomic methods.
- Why might removing an element inside a for-each loop over a HashSet throw ConcurrentModificationException even in a single thread?The for-each uses a fail-fast iterator that tracks modCount. Calling set.remove() structurally modifies the set behind the iterator's back, so on the next iteration it detects the mismatch and throws CME. Use the iterator's own remove() (or removeIf) instead.
- Does Collections.synchronizedSet make a check-then-act operation like 'add if absent' atomic?No. Each individual method is synchronized, but a compound check-then-act spans two calls and another thread can interleave between them. You must hold the lock across the whole operation, or use a concurrent set's atomic add (which returns false if already present).
A HashSet is a shared whiteboard with no rules: if two people write at once, you get a smeared mess. synchronizedSet hands around a single marker (one writer at a time). A concurrent set divides the board into zones so people can write in different zones simultaneously.
- Claiming HashSet is thread-safe because operations are 'fast'
- Thinking synchronizedSet makes iteration or compound actions automatically safe
- Believing the fail-fast iterator reliably catches all concurrency bugs
- Using ConcurrentHashMap.newKeySet() but expecting strongly-consistent snapshot iteration
- ConcurrentHashMap.newKeySet
- Java 1.8
- Set.of
- Java 9
- Set.copyOf
- Java 10
Assumes JDK 27. ConcurrentHashMap.newKeySet dates from Java 8, Set.of from 9 and Set.copyOf from 10, so all of them are on 25 LTS too.
context
- HashSet (Java SE 27 & JDK 27)docs.oracle.com
- ConcurrentHashMap (Java SE 27 & JDK 27)docs.oracle.com
- Set (Java SE 27 & JDK 27)docs.oracle.com