search

Home  >  Q&A  >  body text

java - 读少写多的条件下 ConcurrentHashMap 和 ReadWriteLock 的选择

场景是这样的:两个对象往一个 Map 里循环写入,另外一个对象偶尔读一次,写的频率比读的频率高很多。
希望实现的是读的时候暂停写入。
CocurrentHashMapReadWriteLock 各有什么优劣吗?

PHPzPHPz2804 days ago1184

reply all(2)I'll reply

  • 阿神

    阿神2017-04-17 11:47:10

    should be used ConcurrentHashMap.

    ReadWriteLockApplicable 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.

    reply
    0
  • 高洛峰

    高洛峰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

    reply
    0
  • Cancelreply