Java

ConcurrentHashMap — Thread-Safe Map

admin by @admin ADMIN
16m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The default thread-safe map. Better than `Collections.synchronizedMap` — segmented locking allows multiple readers AND writers. Use `compute`, `merge`, `putIfAbsent` for atomic compound updates.
Java
Raw
import java.util.concurrent.*;

class Counter {
    private final ConcurrentHashMap<String, Long> counts = new ConcurrentHashMap<>();

    public void increment(String key) {
        counts.merge(key, 1L, Long::sum);      // atomic — no separate get/put race
    }

    public Long get(String key) {
        return counts.getOrDefault(key, 0L);
    }

    // compute — atomic read-modify-write with the supplied function
    public void touchLastSeen(String key, long now) {
        counts.compute(key, (k, v) -> (v == null) ? now : Math.max(v, now));
    }

    public static void main(String[] args) throws Exception {
        var c = new Counter();
        var pool = java.util.concurrent.Executors.newFixedThreadPool(8);
        for (int i = 0; i < 8; i++) {
            pool.submit(() -> {
                for (int j = 0; j < 100_000; j++) c.increment("hits");
            });
        }
        pool.shutdown();
        pool.awaitTermination(1, TimeUnit.MINUTES);
        System.out.println(c.get("hits"));     // 800000
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.