I want to understand internally how concurrent modification exception is handled in concurrent collections like ConcurrentHashMap and CopyOnWriteArrayList.
There are so many blogs available in internet which suggest to use these two data structures to avoid concurrent modification exception. But nothing explains , how this exception is internally handled by concurrent collection.
Can someone give more insights on this? I need some detailed explanation.
Here is the
add()method definition ofArrayListandCopyOnWriteArrayList.ArrayList:
CopyOnWriteArrayList:
From the above code, it is clear that
CopyOnWriteArrayListtakes lock before modifying the map. Here I have just posted the code of theaddmethod. If you look on the code ofremove()/addAll()or anymethod which modifiestheListstructurallyyou can see that it takes lock before modifying the collection. Also ArrayList's iterator's method such asnext()/remove()check for modification but for CopyOnWriteArrayList's iterator's method does not check for the modification. For example :ArrayList iterator next() method:
CopyOnWriteArrayList iterator next() method: