简体   繁体   中英

Does ConcurrentHashMap make a copy of itself?

I recently attended an interview where the interviewer asked me question about HashMap and ConcurrentHashMap . After the initial thread-safety benefits I said that it does not throw ConcurrentModificationException when it is being traversed as opposed to HashMap .

The interviewer continued and asked me why it does not throw it. I said that internally HashMap has a variable modCount which keeps the number of modifications done to the map and Iterator is comparing this number against the one it's been initialised with at creation. If this number is different it will throw an exception and this comparison does not happen for ConcurrentHashMap .

He then said ConcurrentHashMap will make a copy of itself when traversing.

I have doubts about this statement since haven't come across this before. Even reading the documentation does not give me a sufficient answer.

Would it make at any point a copy (read or write)?

No it has nothing to do with making a copy of anything. And no throwing ConcurrentModificationException isn't necessarily under multi-threading environment.

Several points regarding to your questions.

  1. ConcurrentModificationException has nothing to do with concurrency (and it actually has a bad name). It's thrown when you are iterating through some data structure and you use the iterator again after making some modification to the structure. This is called fail fast behavior. Due to such behavior it can be thrown under multi-threading context but has no dependency to that at all.

  2. ConcurrentHashMap is a delicated structure and I recommend you to read through it. The way it achieve concurrency is by

    • Any threads accessing different buckets in the map are naturally separated so no need to synchronize between them except for rehashing case.

    • For the threads accessing the same bucket, if the bucket is empty it uses CAS ie AtomicReference to access the only element in the bucket.

    • In case the bucket under operation has hash collision and has multiple elements, its kept as a linked list (except for the case of JDK 1.8 which reworks the link list into a binary tree to achieve better performance under extreme hash collision). The benefit of a linked list is it supports concurrency naturally as long as you operate on the next pointer in CAS way.

There are still a lot of coding art in the ConcurrentHashMap so I suggest you to read its source code thoroughly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM