Alex Rivera | Logout

Concurrent object locks based on ID field

Asked 2009-12-09T10:05:45.990
12

I have a producer/consumer process. The consumed object has an ID property (of type integer), I want only one object with the same ID to be consumed at a time. How can I perform this ?

Maybe I can do something like this, but I don't like it (too many objects created while only one or two with the same ID a day can be consumed and the lock(_lockers) is a bit time consuming :

    private readonly Dictionary<int,object> _lockers = new Dictionary<int,object>();
    private object GetLocker(int id)
    {
        lock(_lockers)
        {
            if(!_lockers.ContainsKey(id))
                _lockers.Add(id,new object());
            return _lockers[id];
        }
    }



    private void Consume(T notif)
    {
            lock(GetLocker(notif.ID))
           {
            ...
           }
    }

enter code here

NB : Same question with the ID property being of type string (in that cas maybe I can lock over the string.Internal(currentObject.ID)

Edit
Report

1 Answer

0

How about assigning IDs from a pool of ID objects and locking on these?

When you create your item:

var item = CreateItem();
ID id = IDPool.Instance.Get(id);
//assign id to object
item.ID = id;

the ID pool creates and maintains shared ID instances:

class IDPool
{ 
    private Dictionary<int, ID> ids = new Dictionary<int, ID>();
    public ID Get(int id)
    {
    //get ID from the shared pool or create new instance in the pool.
    //always returns same ID instance for given integer
    }
}

you then lock on ID which is now a reference in your Consume method:

private void Consume(T notif)
{
       lock(notif.ID)
       {
        ...
       }
}

This is not the optimal solution and only offsets the problem to a different place - but if you believe that you have pressure on the lock you may get a performance improvement using this approach (given that e.g. you objects are created on a single thread, you do not need to synchronize the ID pool then).

answered 2009-12-09T11:29:41.377

Your Answer