How to synchronize on equal keys from different objects in Java

Viewed 74

The method calculate is executed multiple times over different threads. Its result is then saved into a HashMap. Something like that:

void execute(){
     ...
     map.put(key, calculate(key);
}

Data calculate(Key key){
     ...
}

I want to prevent multiple executions over the same key, but I don't want to block all the threads. The ideal solution is to sync calculate over Key. The problem is that Key is not final, I can compare the keys and check if they are equal, but they will be different objects.

How do I solve this?

2 Answers

The computeIfAbsent might be optimistic according to the documentation. If you need a pessimistic solution, you could use striped lock. So you create an array of objects that can be locked and the hash of the key to find the lock.

private final Object[] locks = ....

synchronized(lock(key)){
    ...
}

Object lock(Object key){
      return locks[hashToIndex(key.hashcode())]
}
Related