Java tutorial
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; class ReplaceWorker implements Runnable { public void run() { for (int i = 0; i < 100; i++) { Integer putIfAbsent = Main.map.putIfAbsent("key", Integer.valueOf(1)); if (putIfAbsent == null) return; Main.map.replace("key", putIfAbsent + 1); } } } class MergeWorker implements Runnable { public void run() { for (int i = 0; i < 100; i++) { Main.map.merge("key", Integer.valueOf(1), (ov, nv) -> { return ov + 1; }); } } } public class Main { static ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>(); public static void main(String[] args) { map.put("key", 1); Main test = new Main(); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000)); for (int i = 0; i < 100; i++) { threadPool.submit(new MergeWorker()); } awaitTermination(threadPool); System.out.println(test.map.get("key")); map.put("key", 1); threadPool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000)); for (int i = 0; i < 100; i++) { threadPool.submit(new ReplaceWorker()); } awaitTermination(threadPool); System.out.println(test.map.get("key")); } private static void awaitTermination(ExecutorService threadPool) { try { threadPool.shutdown(); boolean awaitTermination = threadPool.awaitTermination(1, TimeUnit.SECONDS); System.out.println("terminted successfull: " + awaitTermination); } catch (Exception e) { e.printStackTrace(); } } }