番石榴:Cacheloader.load() 是如何工作的

Guava: How does Cacheloader.load() work

假设我有两个线程,线程 A 和线程 B,还有一个 LoadingCache<String, String> 是空的并且有 10 分钟的到期时间。 CacheLoader 用于构建 LoadingCache 及其从数据库中检索的所有内容。

假设LoadingCache仍然是空的并且LoadingCache.get(key)被线程A和线程B同时调用。 CacheLoader.load() 方法会被调用两次吗?

根据我在文档中阅读的内容:

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.

为了验证我的理解,如果线程A和线程B之间有5ms的差异,那么线程A会自动锁定CacheLoader.load()方法,加载值,然后线程B取加载值.这样,就不需要同步了。这样对吗?

不,加载不会被调用两次;其中一个会赢,并且发生与第二种情况相同的事情,即第二个线程等待第一个线程计算出该值,然后获取该值,不需要额外的同步。