Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrency and CacheLoader.load()

Should I synchronize the code in 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? I.e. should I declare my Calculator.calc() method synchronized (or do something else to ensure thread-safety)?

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

like image 353
Fortunato Avatar asked Feb 17 '23 04:02

Fortunato


1 Answers

The depends on the thread-safety of the action in the load method. 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. If it is, don't.

like image 61
John B Avatar answered Feb 27 '23 17:02

John B