[haiku-development] Replacing an element in SynchronizedHashMap

  • From: pulkomandy <pulkomandy@xxxxxxxxxxxxx>
  • To: haiku-development@xxxxxxxxxxxxx
  • Date: Tue, 10 Jun 2014 15:09:12 +0200

Hi,

Consider a SynchronizedHashMap which stores pointers. The map is
considered owning the pointed objects.

With the current API, I see no good way to replace an item in
SynchronizedHashMap without synchronization problems. It's not possible
to get the old value and insert a new one in a single call, so one has
to do something like:

V* object = new V();
V* old = map.Get(k);
map.Put(k, object);
delete old;

There is a problem with this as other threads may access the map and,
for example, remove and delete old before we manage to do it.

The Java API has

V Put(V);

which returns the old values and adds the new one. When used in a
synchronized collection, this is performed with the lock held, which
avoids the problem mentionned above. However, our Put implementation
already uses the return value for error handling.

What should we do to allow this? I can think of:
- Adding status_t Swap(K key, V* val);
        Swaps the element at key with the one pointed by val.
- Adding a way to access the lock directly so it can be held while doing
  the operation
- Leaving this out of SynchronizedHashMap and implement the locking in a
wrapper class

Any of these solutions can also be implemented in a subclass of
SynchronizedHashMap, since the lock has protected visibility, not
private.

Thanks,
-- 
Adrien.

Other related posts: