Java SE API

ConcurrentHashMap.merge()

Atomically merge a value for one key.

Formal Syntax & Structure

java syntaxjava
V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

Working Example

Example Snippetjava
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {    static ThreadPoolExecutor pool(int workers, int capacity) {        return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS,            new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy());    }    static void stop(ExecutorService pool) throws InterruptedException {        pool.shutdown();        try {            if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {                for (Runnable pending : pool.shutdownNow()) {                    if (pending instanceof Future<?> future) future.cancel(false);                }                if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running");            }        } catch (InterruptedException e) {            for (Runnable pending : pool.shutdownNow()) {                if (pending instanceof Future<?> future) future.cancel(false);            }            throw e;        }    }    public static void main(String[] args) throws Exception {        ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();        ThreadPoolExecutor workers = pool(2, 2);        Runnable job = () -> { for (int i = 0; i < 100; i++) counts.merge("book", 1, Integer::sum); };        try {            Future<?> a = workers.submit(job), b = workers.submit(job);            a.get(3, TimeUnit.SECONDS); b.get(3, TimeUnit.SECONDS);            System.out.println(counts.get("book"));            System.out.println(counts.computeIfAbsent("pen", key -> 0));        } finally { stop(workers); }    }}
Java Reference