如何更新 ConcurrentHashMap 线程安全中的值 [英] How to update a Value in a ConcurrentHashMap threadsafe

查看:78
本文介绍了如何更新 ConcurrentHashMap 线程安全中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新 ConcurrentHashmap 中的值,但我不确定如何安全地执行此线程.

I need to update a value in a ConcurrentHashmap but I am not sure on how to do this thread safe.

Hashmap 是一个 ConcurrentHashMap,我需要获取自定义类的实例,对其执行一些操作,然后将更新的值放回去.

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.

有什么办法可以将这个 get-alter-put 操作与原子操作结合起来吗?

Is there any way to combine this get-alter-put operation to something atomic?

提前致谢

推荐答案

您可以使用 ConcurrentHashMaps computeIfPresent https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#computeIfPresent-K-java.util.function.BiFunction-

You can use ConcurrentHashMaps computeIfPresent https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#computeIfPresent-K-java.util.function.BiFunction-

但是由于 computeIfPresent 是一个代价高昂的操作,因为它的原子性和一些更新操作将在 BiFunction 的计算过程中被其他线程阻塞.您可以通过对并发哈希图的读取操作来排除这种情况,该操作非常快,如果返回的不是 null ,则调用 computeIfPrsent

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

下面的代码获取键1"的值并将其加100并以原子方式放回地图

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);
    }

这篇关于如何更新 ConcurrentHashMap 线程安全中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆