如何更新 ConcurrentHashMap 和 return 之前的值

How to update ConcurrentHashMap and return previous value

我有一些函数可以在 ConcurrentHashMap 中增加或设置一个值,这些函数工作正常。我还有一个将值设置为 0 的函数。我希望该函数 return 以前的值。例如,此函数将 return 0 但我想知道它设置为 0

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

如果我这样做,我会收到一条错误消息,指出 ret 必须是最终的。让它成为最终版本不允许我在其中添加值,

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

Map.put returns 旧值,因此您可以使用

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

来自 Map.put 文档:

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.)