Java Collections Java Java API
java.util.Collections
public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s)
Returns a synchronized (thread-safe) NavigableSet backed by the specified NavigableSet.
Without synchronization:
package com.logicbig.example.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 SynchronizedNavigableSetExample { private static AtomicInteger atomicInteger = new AtomicInteger(0); public static void main(String... args) throws InterruptedException { NavigableSet<Integer> theSet = new TreeSet<>(); 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 }}
999
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 }}
1000