How does ConcurrentHashMap work internally?

前端 未结 6 741
傲寒
傲寒 2020-12-02 07:05

I was reading the official Oracle documentation about Concurrency in Java and I was wondering what could be the difference between a Collection returned by

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 07:40

    This is the article that helped me understand it Why ConcurrentHashMap is better than Hashtable and just as good as a HashMap

    Hashtable’s offer concurrent access to their entries, with a small caveat, the entire map is locked to perform any sort of operation. While this overhead is ignorable in a web application under normal load, under heavy load it can lead to delayed response times and overtaxing of your server for no good reason.

    This is where ConcurrentHashMap’s step in. They offer all the features of Hashtable with a performance almost as good as a HashMap. ConcurrentHashMap’s accomplish this by a very simple mechanism. Instead of a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to guard (or lock on) a single bucket of the map. This effectively means that 16 threads can modify the collection at a single time (as long as they’re all working on different buckets). Infact there is no operation performed by this collection that locks the entire map. The concurrency level of the collection, the number of threads that can modify it at the same time without blocking, can be increased. However a higher number means more overhead of maintaining this list of locks.

提交回复
热议问题