Returns a synchronized (thread-safe) NavigableSet backed by the specified NavigableSet.
Using Collections.synchronizedNavigableSet:
package com.logicbig.example.collections;
import java.util.Collections;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SynchronizedNavigableSetExample2 {
private static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String... args) throws InterruptedException {
NavigableSet<Integer> s = new TreeSet<>();
NavigableSet<Integer> theSet = Collections.synchronizedNavigableSet(s);
final ExecutorService e = Executors.newFixedThreadPool(1000);
for (int i = 1; i <= 1000; i++) {
e.execute(() -> {
int n = atomicInteger.incrementAndGet();
try {
theSet.add(n);
} catch (Exception e1) {
//may throw exceptions when not synchronized
System.out.println(e1 + " " + n);
}
});
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
System.out.println(theSet.size());//should be 1000
}
}
Output
1000