场景是这样的:两个对象往一个 Map
里循环写入,另外一个对象偶尔读一次,写的频率比读的频率高很多。
希望实现的是读的时候暂停写入。CocurrentHashMap
和 ReadWriteLock
各有什么优劣吗?
阿神2017-04-17 11:47:10
should be used ConcurrentHashMap
.
ReadWriteLock
Applicable to situations where there are far more reading threads than writing threads, and generally reading will be blocked when there is writing - in this case, it is even worse than a normal lock.
高洛峰2017-04-17 11:47:10
From a simplified programming model point of view, ConcurrentHashMap
should be used, and it can be used to directly generate instances of Map
. With the lock mechanism, you need to manage the status of these locks yourself.
From a performance point of view, ConcurrentHashMap
should also be used, because it has internally optimized the reading and writing operations in blocks. In most cases, reading and writing can be performed at the same time. It's hard to be more efficient on your own. Specific details can be found in this article