public class SynchronizedMapExample2 { private static AtomicInteger counter = new AtomicInteger();
public static void main(String... args) throws InterruptedException { Map<Integer, Integer> m = new HashMap<>(); Map<Integer, Integer> map = Collections.synchronizedMap(m);
final ExecutorService e = Executors.newFixedThreadPool(10); for (int i = 0; i < 10000; i++) { e.execute(() -> map.put(counter.incrementAndGet(), (int) (Math.random() * 100))); } e.shutdown(); e.awaitTermination(1000, TimeUnit.SECONDS); System.out.println(map.size());//should be 10000