There is no ConcurrentHashSet class - ConcurrentHashMap.newKeySet() is the intended way to get a thread-safe set.
Set<Integer> seen = ConcurrentHashMap.newKeySet();
var pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 100; i++) {
int v = i % 20;
pool.submit(() -> seen.add(v));
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("distinct values = " + seen.size());
System.out.println("sorted = " + seen.stream().sorted().limit(5).toList() + " ...");
distinct values = 20
sorted = [0, 1, 2, 3, 4] ...
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30