1

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?

Addev
  • 31,819
  • 51
  • 183
  • 302
  • you must take a lock on the id then. see this answer [1]: http://stackoverflow.com/questions/659915/synchronizing-on-an-integer-value – MLN Oct 12 '12 at 07:55
  • Are your ids really represented as int primitives? if you use an object for your id class, you could synchronize on the ID object itself instead of synchronizing the getItem method.. – Luhar Oct 12 '12 at 07:57
  • I didn't know you can take a mutex from a integer. I have a question about it? What if in another part of the program use the same technique (for other unrelated task) and the ids collide? This could end in a incorrect wait right?. I'm considering to use a SparseArray for handling the locks is correct? – Addev Oct 12 '12 at 07:59
  • 3
    Looks like you are trying to roll your own cache. I advise: don't do it. Look into your framework's caching mechanism(s). – artbristol Oct 12 '12 at 08:13

1 Answers1

1

I guess only way to achieve what you want is to write a Custom Lock using AbstractQueuedSynchronizer which will create lock based on integer you pass but it is highly not recommended

Synchronizing on an Integer value offers solution using ConcurrentHashMap but 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 write Synchronized instance of ConcurrentHashMap which you don't want.

A rather feasible approach would be to increase number of locks.

Community
  • 1
  • 1
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72