问题描述
最近才了解到Guava提供了一个基于内存的缓存(Cache
),但是发现里面并没有类似于ConcurrentMap
的putIfAbsent
方法,请问大家有没有什么替代方案?
问题出现的环境背景及自己尝试过哪些方法
之所以需要这个方法,是因为业务中需要知道缓存中的值是不是当前设置的。我看了文档,里面的建议是使用get(T key, Callable callable)
方法替代putIfAbsent
,但是这还是没办法判断是不是当前写入的
相关代码
现在我的做法如下,想问下各位大佬有没有更优雅的解决方案?
public boolean putIfAbsent(T key) throws ExecutionException {
UpdateChecker updateChecker = new UpdateChecker();
cache.get(key, () -> {
updateChecker.update = true;
return 1;
});
return updateChecker.update;
}
cache.asMap().putIfAbsent(key, value)