Search code examples
javaguavagoogle-guava-cache

How to figure out whether a key exists in guava cache so that I don't overwrite it?


I have a guava cache and I want to figure out whether a particular key already exists or not so that I don't overwrite them? Is this possible to do with 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");
}

Looks like there is no put method that returns boolean where I can figure out whether key already exists. Is there any other way by which I can figure out whether key already exists so that I don't overwrite it?


Solution

  • You can use Cache.asMap() to treat your cache as a Map, thereby exposing additional functionality such as Map.put(), which returns the previously-mapped value:

    if (cache.asMap().put(key, value) != null) {
    

    But that will still replace the previous value. You might want to use putIfAbsent() instead:

    if (cache.asMap().putIfAbsent(key, value) != null) {