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
}
}
Create a free account and build your private vault. Share publicly whenever you want.