public class SynchronizedSetExample { private static AtomicInteger atomicInteger = new AtomicInteger();
public static void main(String... args) throws InterruptedException { Set<Integer> set = new HashSet<>(); System.out.println("initial set size: " + set.size());
final ExecutorService e = Executors.newFixedThreadPool(10); for (int i = 0; i < 1000; i++) { e.execute(() -> set.add(atomicInteger.incrementAndGet())); } e.shutdown(); e.awaitTermination(1000, TimeUnit.SECONDS); System.out.println(set.size());//should be 1000 } }
public class SynchronizedSetExample2 { private static AtomicInteger atomicInteger = new AtomicInteger();
public static void main(String... args) throws InterruptedException { Set<Integer> s = new HashSet<>(); Set<Integer> set = Collections.synchronizedSet(s); System.out.println("initial set size: " + set.size());
final ExecutorService e = Executors.newFixedThreadPool(10); for (int i = 0; i < 1000; i++) { e.execute(() -> set.add(atomicInteger.incrementAndGet())); } e.shutdown(); e.awaitTermination(1000, TimeUnit.SECONDS); System.out.println(set.size());//should be 1000 } }