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?
It depends on whether you want the
updateoperation to be atomic; i.e. whether you want a reader to never see the state of the map when only some of theputoperations have been performed.If
updatedoesn't need to be atomic, then locking is unnecessary. In fact if is an unwanted concurrency bottleneck.If
updateneeds to be atomic, then the lock is necessary. But if you are controlling access with locks, then you don't need to use aConcurrentHashMap. A simpleHashMapwould be better.I don't think that
ConcurrentHashMaphas a way to implement multipleputoperations as an atomic action.