0

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?

ghostrider
  • 2,046
  • 3
  • 23
  • 46
  • 1
    An iteration of a `CopyOnWriteArrayList` can take a long time, so depending on your use case a number of modifications msy be nade while you are iterating. For condistent results you will just keep iterating the old (stale) version that was there when you embarked on the iteration. Random access takes but a moment, so leaves no old versions. But two random accesses may not access the same version, there can always come a write between them. So accessing neighbouring indices may not give you neighbouring elements, for example. – Ole V.V. Dec 20 '19 at 04:55
  • 1
    The comment has been deleted. (Which could mean that the person who wrote it regrets having written it.) But it isn't saying that `CopyOnWriteArrayList` is unsuitable for random access reads, or that `ReadWriteLock` is a *better* option. It is just saying that it is an option if you don't need to do traversals. The *best* option depends on things like the size of the list, the frequency of updates, the expected read performance, and whether you need the specific guaranteed iteration semantics of `CopyOnWriteArrayList`. This is not something you can reduce to a simple rule of thumb. – Stephen C Dec 20 '19 at 08:28

1 Answers1

1

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.

Gawain
  • 1,017
  • 8
  • 17