@SneakyThrows
public static void main(String[] args) {
LoadingCache<String, String> cache = Caffeine.newBuilder()
.maximumSize(5)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(key -> {
// 加载时,睡眠一秒
Thread.sleep(1000);
return key + System.currentTimeMillis();
});
// 异步线程加载
new Thread(() -> {
System.out.println("执行get");
cache.get("key");
}).start();
// 异步线程移除
new Thread(() -> {
// 睡眠,让这个线程后执行
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行invalidate");
cache.invalidate("key");
}).start();
// 按程序逻辑来说,我们应该拿到的结果是空map
Thread.sleep(1200);
System.out.println(cache.asMap());
}
@SneakyThrows
public static void main(String[] args) {
LoadingCache<String, String> cache = Caffeine.newBuilde