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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With