How does ConcurrentHashMap work internally?

I would read the source of ConcurrentHashMap as it is rather complicated in the detail. In short it has

  • Multiple partitions which can be locked independently. (16 by default)
  • Using concurrent Locks operations for thread safety instead of synchronized.
  • Has thread safe Iterators. synchronizedCollection's iterators are not thread safe.
  • Does not expose the internal locks. synchronizedCollection does.

The ConcurrentHashMap is very similar to the java.util.HashTable class, except that ConcurrentHashMap offers better concurrency than HashTable or synchronizedMap does. ConcurrentHashMap does not lock the Map while you are reading from it. Additionally,ConcurrentHashMap does not lock the entire Mapwhen writing to it. It only locks the part of the Map that is being written to, internally.

Another difference is that ConcurrentHashMap does not throw ConcurrentModificationException if the ConcurrentHashMap is changed while being iterated. The Iterator is not designed to be used by more than one thread though whereas synchronizedMap may throw ConcurrentModificationException