番石榴:Cacheloader.load()如何工作 [英] Guava: How does Cacheloader.load() work

查看:744
本文介绍了番石榴:Cacheloader.load()如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个线程,线程A和线程B,以及一个LoadingCache<String, String>,该线程为空并且有10分钟的到期时间. CacheLoader用于构建LoadingCache,它所做的全部工作都从数据库中检索出来.

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.

假定LoadingCache仍然为空,并且LoadingCache.get(key)由线程A和线程B同时调用. CacheLoader.load()方法会被调用两次吗?

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:

如果当前正在再次调用get(K)或getUnchecked(K), 键的值,只需等待该线程完成并返回其值 加载的值.请注意,多个线程可以同时加载值 以获得不同的键.

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之间存在5毫秒的差异,则线程A将自动锁定CacheLoader.load()方法,加载该值,然后线程B会选择加载的值.这样,就不需要同步了.是这样吗?

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.

这篇关于番石榴:Cacheloader.load()如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆