Guava: how Cacheloader.load () works

Suppose I have two threads: Thread A and Thread B and LoadingCache<String, String>that is empty and expires 10 minutes. A was CacheLoaderused to create LoadingCacheeverything that it extracts from the database.

Suppose it LoadingCacheis still empty, and LoadingCache.get(key)was called by thread A and thread B at the same time. Call the method CacheLoader.load()twice?

From what I read in the docs:

If another call to get (K) or getUnchecked (K) is currently loading the value for the key, it simply waits for this stream to complete and returns its loaded value . Note that multiple threads can simultaneously load values โ€‹โ€‹for individual keys.

To test my understanding, if there is a 5 ms difference between Thread A and Thread B, then Thread A will automatically lock the method CacheLoader.load(), load the value, and then Thread B will simply load the loaded value. In this case, synchronization is not required. Is it correct?

0
source share
1 answer

No, the download will not be called twice; one of them will win, and the same thing will happen as in your second case, since the second thread waits until the first thread calculates this value, and then selects this value without requiring additional synchronization.

+2
source

Source: https://habr.com/ru/post/1599193/


All Articles