我定义了以下内容
private ConcurrentMap<Integer, AtomicInteger> = new ConcurrentHashMap<Integer, AtomicInteger>();
private void add() {
staffValues.replace(100, staffValues.get(100), new AtomicInteger(staffValues.get(100).addAndGet(200)));
}
经过测试,我得到的值不是预期的,我认为这里存在竞争条件。有谁知道通过将 get 调用包装在替换函数中是否会被认为是线程安全的?
最佳答案
处理此类情况的一个好方法是使用 computeIfAbsent
方法(不是@the8472推荐的compute
方法)
computeIfAbsent
接受 2 个参数、键和 Function<K, V>
仅当现有值丢失时才会被调用。由于 AtomicInteger 是线程安全的,可以从多个线程递增,因此您可以通过以下方式轻松使用它:
staffValues.computeIfAbsent(100, k -> new AtomicInteger(0)).addAndGet(200);
关于java - 添加到 ConcurrentHashMap 中的 AtomicInteger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821040/