javacollectionscopyonwritearraylist

CopyOnWriteArrayList suitable only for iterations and not random access reads


I came across below comment on this question thread :

Because the CopyOnWriteArrayList is for safe traversals. The cost of using it is duplicating the underlying array of references for each modification and possibly retaining multiple copies for threads iterating over stale versions of the structure. A ReadWriteLock would allow multiple readers and still let the occasional writer perform the necessary modifications

I have just started learning about CopyOnWriteArrayList, can someone please elaborate what does the above statement mean?How does a random access read instead of iteration, make the ReadWriteLock a better option?


Solution

  • When you use iterator to traversal the CopyOnWriteArrayList, you will get a snapshot of list when you calling the iterator(), and future modification will not affect your snapshot so you will always loop through the data copy from the time you call iterator.

    For random access loop, it will get the data from current fresh copy of list. And if some modification occurs, the future random access will read the modified list and may cause some synchronize problems. So a ReadWriteLock will be helpful here to make the traversal thread-safe.