I have a class for loading from persistence items with the following method at PersistenceController class:
Item loadItem(int id);
So now I want to implement the following method in other controller:
synchronized Item getItem(int id){
Item result= getItemFromMemory(id);
if (result==null){
result=PersistenceController.loadItem(id);
}
return result;
}
The goal is to ensure only one (or zero) instances of a item with the same id in memory at the same time. This method works but have one problem: Every load Item must wait for each other. I’d like to change the synchronization scheme in order to a call wait for other only if both have the same id.
Whats the best way to do this?
I guess only way to achieve what you want is to write a
Custom LockusingAbstractQueuedSynchronizerwhich will create lock based on integer you pass but it is highly not recommendedSynchronizing on an Integer value offers solution using
ConcurrentHashMapbut it has its own flaws. You can not delete the value from map when you have acquired same lock so there is no possible way to delete value unless you writeSynchronizedinstance ofConcurrentHashMapwhich you don’t want.A rather feasible approach would be to increase number of locks.