I need to have a number of threads which operate on the shared java.util.HashMap.
Each of them will perform single read and write operations (i.e. none will use bulk operations, like putAll()
) and I want to make sure there will be no lost updates.
Does synchronized writing guarantees safety? If I do something like this:
writeLock.lock();
double latestValue = map.get(key);
map.put(key, latestValue + diff);
writeLock.unlock();
Will it be enough to avoid lost updates? Will the same approach be enough to achieve repeatable reads?
And, if I used ConcurrentHashMap
, can I get rid of my locks
safely?
UPD: is there any linear overhead in memory usage if I switch from HashMap to ConcurrentHashMap?