joh*_*ohn 2 java guava google-guava-cache
我有一个番石榴缓存,我想弄清楚某个特定的密钥是否已经存在,这样我就不会覆盖它们?这可能与番石榴缓存有关吗?
private final Cache<Long, PendingMessage> cache = CacheBuilder.newBuilder()
.maximumSize(1_000_000)
.concurrencyLevel(100)
.build()
// there is no put method like this
if (cache.put(key, value) != null) {
throw new IllegalArgumentException("Message for " + key + " already in queue");
}
Run Code Online (Sandbox Code Playgroud)
看起来没有返回布尔值的 put 方法,我可以在其中确定键是否已经存在。有没有其他方法可以确定密钥是否已经存在,这样我就不会覆盖它?
您可以使用Cache.asMap()将缓存视为Map,从而公开其他功能,例如Map.put(),它返回先前映射的值:
if (cache.asMap().put(key, value) != null) {
Run Code Online (Sandbox Code Playgroud)
但这仍然会取代之前的值。您可能想改用putIfAbsent():
if (cache.asMap().putIfAbsent(key, value) != null) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6655 次 |
| 最近记录: |