Violetta
Violetta

Reputation: 603

ConcurrentHashMap and ReentrantReadWriteLock

I have one thread that updates data in Map and several threads that read this data. 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?

Upvotes: 1

Views: 892

Answers (1)

Stephen C
Stephen C

Reputation: 718798

Can I use only ConcurrentHashMap in this situation?

It depends on whether you want the update operation to be atomic; i.e. whether you want a reader to never see the state of the map when only some of the put operations have been performed.

  • If update doesn't need to be atomic, then locking is unnecessary. In fact if is an unwanted concurrency bottleneck.

  • If update needs to be atomic, then the lock is necessary. But if you are controlling access with locks, then you don't need to use a ConcurrentHashMap. A simple HashMap would be better.

I don't think that ConcurrentHashMap has a way to implement multiple put operations as an atomic action.

Upvotes: 3

Related Questions