I need to update a value in a ConcurrentHashmap but I am not sure on how to do this thread safe.
The Hashmap is a ConcurrentHashMap and I need to get the instance of the custom class, perform some operations on it and then put the updated value back in.
Is there any way to combine this get-alter-put operation to something atomic?
Thanks in advance
You can use ConcurrentHashMaps computeIfPresent https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#computeIfPresent-K-java.util.function.BiFunction-
But since computeIfPresent is a costly operation as its atomic and some update operations will be blocked by other threads during the computation of the BiFunction . You can preclude this with a read operation on concurrent hashmap which is pretty fast and if that returns not null , invoke computeIfPrsent
Below code gets the value of key "1" and adds 100 to it and puts in back to the map in a atomic way
ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
map.put(1,100);
Integer value = map.get(1);
if (value != null)
map.computeIfPresent(1, (key, oldValue) -> oldValue + 100);
}