实现说明
computeIfAbsent 每键一次的核心是类 ProfileCache、Profile和函数 main。
for (int i = 0; i < 12; i++) 是唯一的迭代点——其余代码顺序执行一遍。try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。
使用要点
- 跑完文件,输出里会留下标记——
cache size:、profile loads:、value:。
常见问题
运行「computeIfAbsent 每键一次」会打印什么?
运行文件本身,cache size:、profile loads:、value: 这些前缀各对应一段演示逻辑。
核心语句
return new Profile("Ada " + key);
代码示例
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());
}
}