简体   繁体   English

如何锁定单个ConcurrentHashMap对象以进行修改而不会阻塞整个地图?

[英]How to lock on single ConcurrentHashMap object for modification without blocking whole map?

Is there an easy way to lock on ConcurrentHashMap object during its modification without blocking whole map? 有没有一种简单的方法可以在其修改过程中锁定ConcurrentHashMap对象而不会阻塞整个地图? As far as I know here is simple way in Java 8 - method competeIfPresent , but unfortunately I've got 1.7 java on project. 据我所知,这是Java 8中的一种简单方法-方法compareIfPresent ,但是不幸的是我在项目上有1.7 java。

private Map<Long, AtomicInteger> idForCountMap;

public void decrement(Long id) {
    AtomicInteger count = idForCountMap.get(id);
    if (count != null){
    count.decrementAndGet();
    // do some additional operations
    }
}

Here is an example. 这是一个例子。 How can I perform decrement opeperation as atomic one WITHOUT blocking whole map? 如何在不阻塞整个地图的情况下以原子方式执行减量运算?

ps suppose it's quite common situation, but I could not find fine explained answer. ps认为这是很普遍的情况,但是我找不到很好的解释的答案。

I think it will workout if you can bring a shared key for the mapped value, and acquire a lock on the key for the complete operation. 我认为,如果您可以为映射的值带来一个共享密钥,并为完成整个操作获得一个锁,它将可以锻炼身体。

public void decrement(SharedKey id) {
synchronized(id){
     AtomicInteger count = idForCountMap.get(id);
     if (count != null){
        count.decrementAndGet();
        // do some additional operations
     }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM