实现说明
除了类 SafeCacheLoad和函数 main,文件里再无其他定义。
IllegalStateException 在 try 块内抛出——谁来接住由匹配的 except 子句决定,与任何输入检查无关。
使用要点
- 构造上就无依赖——没有注册表,没有锁文件条目。
- 直接运行文件,输出会带上标签,比如
null mapping -> result=、first load failed:、key present after exception:——输出的每一行都能指回产生它的那次调用。
常见问题
这个示例会校验输入吗?
不会——IllegalStateException 在 try 块内抛出:执行到这一行就必然抛出,由外围的 except 子句决定谁来接住。示例里没有输入校验。
运行「ConcurrentHashMap.computeIfAbsent 失败路径」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 null mapping -> result=、first load failed:、key present after exception: 这类标签。
签名一览:public static void main(String[] args)
核心语句
throw new IllegalStateException("upstream down");
return "token-v" + attempts.get();
代码示例
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class SafeCacheLoad {
public static void main(String[] args) {
ConcurrentHashMap<String, String> tokens = new ConcurrentHashMap<>();
AtomicInteger attempts = new AtomicInteger();
// Returning null leaves the key absent (no null entries cached)
String missing = tokens.computeIfAbsent("guest", k -> null);
System.out.println("null mapping -> result=" + missing + " size=" + tokens.size());
// Throwing inside the mapping function aborts insertion cleanly
try {
tokens.computeIfAbsent("svc-a", k -> {
attempts.incrementAndGet();
throw new IllegalStateException("upstream down");
});
} catch (IllegalStateException ex) {
System.out.println("first load failed: " + ex.getMessage());
}
System.out.println("key present after exception: " + tokens.containsKey("svc-a"));
// Subsequent call retries and populates the key once
String loaded = tokens.computeIfAbsent("svc-a", k -> {
attempts.incrementAndGet();
return "token-v" + attempts.get();
});
String cached = tokens.computeIfAbsent("svc-a", k -> "unused");
System.out.println("loaded=" + loaded + " cached=" + cached + " attempts=" + attempts.get());
}
}