Normally I would lock on a critical section like the following.
public class Cache {
private Object lockObject = new Object();
public Object getFromCache(String key) {
synchronized(lockObject) {
if (cache.containsKey(key)) {
// key found in cache - return cache value
}
else {
// retrieve cache value from source, cache it and return
}
}
}
}
The idea being I avoid a race condition which could result in the data source being hit multiple times and the key being added to the cache multiple times.
Right now if two threads come in at about the same time for different cache keys, I will still block one.
Assuming the keys are unique - will the lock still work by locking on the key?
I think it won't work because I understand that the object reference should be the same for the lock to come into effect. I guess this comes down to how it checks for equality.
public class Cache {
public Object getFromCache(String key) {
synchronized(key) {
if (cache.containsKey(key)) {
// key found in cache - return cache value
}
else {
// retrieve cache value from source, cache it and return
}
}
}
}