user379151
user379151

Reputation: 1379

Guava cache get and put behavior

I know there is lot of documentation on Guava Cache, but haven't been able to find a clear answer to this Q - An entry exists in cache already and I overwrite the entry with - cache.put(K,V)

If another thread calls cache.get(K) at the same time, what does the cache return? Is it blocked till put() completes writing or does it return the old value? Any helpful links/pointers are appreciated.

Upvotes: 1

Views: 631

Answers (1)

Petr Janeček
Petr Janeček

Reputation: 38444

Guava's Cache classes are based on ConcurrentHashMap and therefore share its basic behaviour.

I don't think it's a part of the contract, but it's mentioned in one of the docs. To make sure, I looked at the source code and it indeed is the case - the code is actually branched from ConcurrentHashMap. We will have to have somebody from the Guava team chime in to be absolutely sure there are no corner cases where this might be false, so I'll just silently assume it's always right.

With this in mind, the answer is easy - the ConcurrentHashMap docs say:

Retrieval operations (including get()) generally do not block, so may overlap with update operations (including put() and remove()). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll() and clear(), concurrent retrievals may reflect insertion or removal of only some entries.

Therefore, in your particular case, the get() call will not block and will most likely return the old value.

Upvotes: 4

Related Questions