简体   繁体   English

ConcurrentHashMap 和 ReentrantReadWriteLock

[英]ConcurrentHashMap and ReentrantReadWriteLock

I have one thread that updates data in Map and several threads that read this data.我有一个线程更新Map中的数据,还有几个线程读取这些数据。 Now my code looks like this:现在我的代码如下所示:

public class Updater {
    private ConcurrentMap<String, Integer> valuesMap = new ConcurrentHashMap<>();
    private ReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    public void update(Settings settings) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            for (Map.Entry<String, Integer> entry : valuesMap.entrySet()) {
                valuesMap.put(entry.getKey(), 
                              entry.getValue() + settings.getUpdateValue());
            }
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
    }

    public Integer getValue(String key) {
        reentrantReadWriteLock.readLock().lock();
        try {
            return valuesMap.get(key);
        } finally {
            reentrantReadWriteLock.readLock().unlock();
        }
    }
}

But I think I overdid it.但我觉得我做得过火了。 Can I use only ConcurrentHashMap in this situation?在这种情况下我可以只使用ConcurrentHashMap吗?

Can I use only ConcurrentHashMap in this situation?在这种情况下我可以只使用ConcurrentHashMap吗?

It depends on whether you want the update operation to be atomic;这取决于您是否希望update操作是原子的; ie whether you want a reader to never see the state of the map when only some of the put operations have been performed.即当只执行了一些put操作时,您是否希望读者永远不会看到 map 的 state。

  • If update doesn't need to be atomic, then locking is unnecessary.如果update不需要是原子的,那么锁定是不必要的。 In fact if is an unwanted concurrency bottleneck.事实上,如果是一个不需要的并发瓶颈。

  • If update needs to be atomic, then the lock is necessary.如果update需要是原子的,那么锁是必要的。 But if you are controlling access with locks, then you don't need to use a ConcurrentHashMap .但是,如果您使用锁来控制访问,那么您不需要使用ConcurrentHashMap A simple HashMap would be better.一个简单的HashMap会更好。

I don't think that ConcurrentHashMap has a way to implement multiple put operations as an atomic action.我认为ConcurrentHashMap没有办法将多个put操作实现为原子操作。

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

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