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();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>