Search code examples
javajava-8concurrenthashmap

How to update ConcurrentHashMap and return previous value


I have some functions that increment or set a value in a ConcurrentHashMap which are working fine. I also have a function that sets a value to 0. I would like that function to return the previous value. As an example, this function will return 0 but I would like to know the value before it was set to 0

public static long zeroValue(String mapKey) {
    return concurrentMap.compute(mapKey, (key, val) -> 0L);
}

If I do this I get an error that ret must be final. Making it final then doesn't allow me to put a value in it though,

public static long zeroValue(String mapKey) {
    long ret;
    concurrentMap.compute(mapKey, (key, val) -> { ret = val; return 0L; });
    return ret;
}

Solution

  • Map.put returns the old value, so instead of compute you could use

    public static long zeroValue(String mapKey) {
        return concurrentMap.put(mapKey, 0L);
    }
    

    From Map.put documentation:

    Returns: the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)