ConcurrentHashMap ComputeIfAbsent Once
Initialize per-key values with ConcurrentHashMap.computeIfAbsent, whose contract guarantees the mapping function runs at most once per key under concurrency.
Code
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ProfileCache {
record Profile(String name) {}
public static void main(String[] args) {
ConcurrentHashMap<String, Profile> cache = new ConcurrentHashMap<>();
AtomicInteger loads = new AtomicInteger();
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
// 12 个线程抢同一个 key:映射函数只在第一次缺失时执行
for (int i = 0; i < 12; i++) {
pool.execute(() -> cache.computeIfAbsent("u1", key -> {
loads.incrementAndGet();
return new Profile("Ada " + key);
}));
}
} // close() 会等全部任务跑完
// computeIfAbsent 的契约:对同一 key 至多执行一次映射函数
System.out.println("cache size: " + cache.size());
System.out.println("profile loads: " + loads.get());
System.out.println("value: " + cache.get("u1").name());
}
}How it works
Count the classes ProfileCache and Profile and the function main as the entire surface area of ConcurrentHashMap ComputeIfAbsent Once.
The cycling part of this snippet is for (int i = 0; i < 12; i++). The try-with-resources form guarantees each declared resource is closed even when the body throws.
Using it
Running the file prints labeled results such as cache size:, profile loads:, value: — each operation’s effect is visible in the output.
Key statements
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
// 12 个线程抢同一个 key:映射函数只在第一次缺失时执行
for (int i = 0; i < 12; i++) {
pool.execute(() -> cache.computeIfAbsent("u1", key -> {
loads.incrementAndGet();
return new Profile("Ada " + key);
}));
}
} // close() 会等全部任务跑完
Interactive Tools for This Topic
FAQ
- What does ConcurrentHashMap ComputeIfAbsent Once print when run?
- No setup needed: run the file and look for labeled lines like `cache size:`, `profile loads:`, `value:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.