2

I have tons of update operation on ConcurrentHashMap and I need to minimize synchronization for update this map.

please see code below.

public ConcurrentHashMap<String, Integer> dataMap = new ConcurrentHashMap<>();

    public void updateData(String key, int data) {
        if ( dataMap.containsKey(key)) {
            // do something with previous value and new value and update it
        }
    }

For example, When one thread calls updateData with Key "A", then every other try calling updateData with key "A" should be blocked until first thread is done. meanwhile, I want another thread trying to call updateData with key "B" runs concurrently.

I wonder if there is any fancy way to lock hashMap simply with its key.

BinaryProbe
  • 273
  • 4
  • 12
  • 1
    Is there any issue without synchronization? I guess the `put` operation of ConcurrentHashMap internally uses `synchronization` over the segment. You don't have to do it explicitly – Neenad May 15 '19 at 04:27
  • 2
    If you use `computeIfPresent`, the synchronization is over single keys iiuc. – daniu May 15 '19 at 04:29

1 Answers1

1

I think you are looking for the compute method.

It takes a function that is given the key and the current value (or null if there is no value yet), and can compute the new value.

ConcurrentHashMap guarantees that only one such functions runs at the same time for the given key. A concurrent second call will block until ready.

Thilo
  • 257,207
  • 101
  • 511
  • 656