3

I went through many pages on the web to understand the working of ConcurrentHashMap and how it clones the actual map to iterate. This manages to get the Weakly Consistent property.

Now, while iterating if I call the remove() method, then at what stage is this change reflected in the main collection?

Basically, want to understand how the clone and main collection are merged?

Is it done once the iteration is complete?

vijayinani
  • 2,548
  • 2
  • 26
  • 48

2 Answers2

0

First, ConcurrentHashMap don't make copy to iterate, see ConcurrentHashMap#entrySet.

Second, the change of remove reflect to the collection immediately, see ConcurrentHashMap#BaseIterator#remove.

Dean Xu
  • 4,438
  • 1
  • 17
  • 44
0

The idea is that ConcurrentHashMap uses buckets, like any other hash-based structure. When you lookup (remove) an entry, it uses the hashCode to find that bucket where the entry might reside first and then remove it immediately.

The question is, will you be able to spot/see this removal that actually happened; for example you iterate and print the contents of CHM and remove some of the entries at the same time. If you already "visited" some bucket via forEach for example (and traversal happens on bucket-to-bucket basis), and the entry was removed from that bucket - you will not spot it.

On the other hand if you will remove and entry from a "yet to be visited" bucket - you will spot the removal.

That is for example the reason that size returns a "at the moment" known size - it counts for example entries from bucketA, then later someone remove some of those entries, CHM will not get back or synchronize to count those again.

Also some very good comments to read here

Eugene
  • 117,005
  • 15
  • 201
  • 306