简体   繁体   English

并发和CacheLoader.load()

[英]Concurrency and CacheLoader.load()

Should I synchronize the code in CacheLoader.load()? 我应该同步CacheLoader.load()中的代码吗?

I have code like this: 我有这样的代码:

final Calculator calculator = new Calculator();

final LoadingCache<Key, Value> cache = CacheBuilder.newBuilder().build(new CacheLoader<Key, Value>(){
        @Override
        public Value load(final Key key) throws Exception {
            return calculator.calc(key);
        }} );

If the cache needs to load the values of two different keys from two different threads do I have to worry about thread interference in my Calculator object? 如果缓存需要从两个不同的线程加载两个不同键的值,我是否需要担心我的Calculator对象中的线程干扰? Ie should I declare my Calculator.calc() method synchronized (or do something else to ensure thread-safety)? 即我应该声明我的Calculator.calc()方法是同步的(或做其他事情以确保线程安全)?

Edit 编辑

Just so that it is clear I am asking specifically with regards to caching in Guava: http://code.google.com/p/guava-libraries/wiki/CachesExplained 就这样我很明确地询问Guava中的缓存问题: http//code.google.com/p/guava-libraries/wiki/CachesExplained

The depends on the thread-safety of the action in the load method. 这取决于load方法中操作的线程安全性。 It IS possible for it to be executed concurrently for different keys. 它可以同时针对不同的密钥执行。 Therefore if the action is not thread-safe, it should be made so in some way (synchronizing being the most trivial option). 因此,如果操作不是线程安全的,那么它应该以某种方式进行(同步是最简单的选项)。

So, if calculator.calc(key) is not thread-safe, synchronize it. 因此,如果calculator.calc(key)不是线程安全的,请同步它。 If it is, don't. 如果是,不要。

If threads are going only to read, then you don't have to synchronize. 如果线程只是要读取,那么您不必同步。 If the threads are going to manipulate the value of the cache, then both read and write operations should be synchronized. 如果线程将操纵缓存的值,则应同步读取和写入操作。

Thanks to everyone who answered. 感谢所有回答的人。

I have checked this with a little test program and there IS thread interference. 我用一个小测试程序检查了这个并且存在线程干扰。 Specifically for different keys when the CacheLoader has to be invoked, these calls are not synchronized so if Calcualtor.calc() is not thread-safe, then weird results will ensue. 特别是对于必须调用CacheLoader时的不同键,这些调用不同步,因此如果Calcualtor.calc()不是线程安全的,那么将会产生奇怪的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM