Java – write lock to HashMap
I have an asynchronously updated HashMap I need to perform operations involving the map, which requires that the map does not change state during the task, such as sorting values based on the map content
Is there a way to lock a map so that only reads blocking all write threads occur, so all modifications will occur after unlocking the map? Locks need to be able to allow multiple threads to write while I use concurrent HashMap, and I want to take advantage of the benefits of concurrent HashMap
Solution
Concurrent HashMap does not provide thread safety between method calls, only within a single call Therefore, if you want to keep the mapping unchanged during the operation, you need to wrap the call in the map with your own lock
For example, using readwritelock:
ReadWriteLock readWriteLock = new reentrantreadwritelock();
When you update the map
readWriteLock.writeLock().lock(); // do the updates readWriteLock.writeLock().unlock();
When you want to read from the map
readWriteLock.readLock().lock(); // perform the read and its operations that rely on the map not changing readWriteLock.readLock().unlock();