【问题标题】:How to update ConcurrentHashMap and return previous value如何更新 ConcurrentHashMap 并返回之前的值
【发布时间】:2021-09-07 04:57:54
【问题描述】:

我有一些函数可以在ConcurrentHashMap 中增加或设置一个值,这些函数工作正常。我还有一个将值设置为0 的函数。我希望该函数返回以前的值。例如,此函数将返回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;
}

【问题讨论】:

    标签: java java-8 concurrenthashmap


    【解决方案1】:

    Map.put 返回旧值,因此您可以使用 compute 代替

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

    来自Map.put 文档:

    返回: 与 key 关联的前一个值,如果没有 key 映射,则返回 null。 (如果实现支持 null 值,则返回 null 还可以指示映射先前将 null 与 key 关联。)

    【讨论】:

    • 完美,谢谢。我陷入了假设解决方案会很困难的陷阱,所以我开始寻找复杂的解决方案:-)
    • @MikeKulls 另外,在值为常量的情况下,最好使用putcompute 需要一个不需要的 lambda
    • 谢谢,好建议。这些用于具有 15 个线程的大容量数据流情况,因此每次节省都会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2020-09-18
    • 2019-02-20
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    相关资源
    最近更新 更多