[haiku-development] Re: Replacing an element in SynchronizedHashMap

  • From: Ingo Weinhold <ingo_weinhold@xxxxxx>
  • To: haiku-development@xxxxxxxxxxxxx
  • Date: Tue, 10 Jun 2014 19:49:38 +0200

On 10.06.2014 15:09, pulkomandy wrote:
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

Is there a SynchronizedHashMap other than this [1] one you're talking about? Because this one does inherit BLocker publicly.

CU, Ingo

http://cgit.haiku-os.org/haiku/tree/headers/private/shared/HashMap.h#n207


Other related posts: