2

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?

john
  • 11,311
  • 40
  • 131
  • 251

1 Answers1

7

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) {
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • what is the difference between `cache.put` vs `cache.asMap().put` vs `cache.asMap().putIfAbsent`? What I mean is - In one case we use put directly on cache and in other it calls asMap() and then calls put on it? – john Jan 11 '18 at 03:37
  • @john `Map.put()` returns the previous value. See my update. – shmosel Jan 11 '18 at 03:40
  • I found this note in the documentation: **Note that although the view is modifiable, no method on the returned map will ever cause entries to be automatically loaded.** – Miss Chanandler Bong Apr 05 '23 at 08:58