简体   繁体   中英

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? As far as I know here is simple way in Java 8 - method competeIfPresent , but unfortunately I've got 1.7 java on project.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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