Assume that I have two threads, Thread A and Thread B, and a LoadingCache<String, String>
that is empty and has an expiration of 10 minutes. A CacheLoader
was used to build the LoadingCache
and all it does it retrieve from the database.
Assume that the LoadingCache
is still empty and LoadingCache.get(key)
was invoked by Thread A and Thread B simultaneously. Will the CacheLoader.load()
method get called twice?
From what I've read in the docs:
If another call to get(K) or getUnchecked(K) is currently loading the value for key, simply waits for that thread to finish and returns its loaded value. Note that multiple threads can concurrently load values for distinct keys.
To verify my understanding, if there is a 5ms difference between Thread A and Thread B, then Thread A will automatically lock the CacheLoader.load()
method, loads the value, then Thread B just picks up the loaded value. With this, synchronization isn't necessary. Is this right?
No, load will not get called twice; one of them will win, and the same thing happens as in your second case, which is that the second thread waits until the first thread computes the value, and then picks up that value, no extra synchronization required.