0

I want to get & remove an item from Cache

final Cache<String, PendingRequest> pendingRequest = CacheBuilder.newBuilder().build();

// get first
pendingCall = pendingRequest.getIfPresent(key);
pendingRequest.invalidate(key); // then remove.

I also found another way

pendingCall = pendingRequest.asMap().remove(key);

Does asMap method clone all the items? Is it a heavy call? Which manner is better if considering performance.

Mr.Wang from Next Door
  • 13,670
  • 12
  • 64
  • 97

1 Answers1

2

There's no real difference between those calls because Cache#asMap() is defined as:

Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to the map directly affect the cache.

Calling asMap() may be slightly less performant (because it's possible a view has to be created) but the time is constant (and negligible) and is an implementation detail (see internal Guava LocalCache and LocalManualCache classes for more details).

What's more important, Cache#invalidate(K) is more idiomatic and I'd recommend using it instead of map view methods (edit after @BenManes' comment below) if you don't need returned value associated with the key, otherwise use map view.

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
  • 3
    While more idiomatic, the view is useful in the situation where the removed value is needed. This operation is atomic, whereas his alternative of performing two operations is racy. The Cache interface provides an idiomatic and simple abstraction, while the view provides an escape hatch for more advanced needs. – Ben Manes Apr 14 '17 at 16:39
  • @BenManes You're right, I didn't catch that OP needed to use removed value. – Grzegorz Rożniecki Apr 17 '17 at 15:31