Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does google Guava LoadingCache do when a call is made to invalidate while load is executing?

I have a Google guava cache that is loading data from the database and caching it using the primary key. The objects I end up creating from the database are immutable and building an object requires access to several tables. What happens in the following scenario:

  • Thread 1: calls cache.load(10) and the cache is being populated based on a database primary key with value 10
  • Thread 2: updates the database row with primary key 10 and so it calls cache.invalidate(10) the invalidate is called before the cache.load(10) is finished.

What does Guava Loading Cache do when invalidate(x) is called while load(x) is executing?

like image 501
ams Avatar asked Oct 14 '12 16:10

ams


2 Answers

As currently specified in the Javadoc "No observable state associated with this cache is modified until loading completes". The semantics of loading are further specified as "Newly loaded values are added to the cache using Cache.asMap().putIfAbsent after loading has completed."

You can also read the code to see where loading entries are ignored when invalidate or remove are called.

like image 160
fry Avatar answered Sep 28 '22 02:09

fry


You can have two situations there:

  • Thread 1 reached the point of the actual loading (LocalCache.Segment.lockedGetOrLoad() in 13.0.1) first, and the segment lock was acquired: in that case, the loading finishes, the lock is released and the computed value is returned to the caller, but it will be invalidated by Thread 2 when it runs (LocalCache.Segment.remove()) and can acquire the lock.

  • Thread 2 acquired the lock before Thread 1 actually started loading: the invalidation doesn't really do anything, since the entry's not there yet, and Thread 1 then loads the up-to-date value.

like image 41
Frank Pavageau Avatar answered Sep 28 '22 00:09

Frank Pavageau