0

I can't find any explanation on SO about when it's applicable to use CopyOnWriteArrayList, I mean in what situation the container suits best.

There is a question with same title, In what situations is the CopyOnWriteArrayList suitable?. However, it's closed because it duplicates against other question thread. I think both threads haven't answered the question so I launched this question thread.

For In what situations is the CopyOnWriteArrayList suitable?, it actually illuminates that the CopyOnWriteArrayList is

very efficient if you have a List where Iteration outnumber mutation

But I didn't find the actual application scenario. For How can CopyOnWriteArrayList be thread-safe?, it actually focuses on the reason why the CompyOnWriteArrayList is thread safe.

Thanks for your answer in advance.

Eugene
  • 10,627
  • 5
  • 49
  • 67
  • @JoeC Thanks for the comment but as I mentioned above, I didn't find the satisfied answer in both the "In what situations is the CopyOnWriteArrayList suitable" and the other duplicate thread it points to. And actually, the duplicate thread "How can CopyOnWriteArrayList be thread-safe?" is truly another story. That's the reason why I launched this thread. Thanks. – Eugene Oct 22 '17 at 12:47
  • Then please [edit] your question to clarify exactly why the answer there does not answer your question, because to me it looks like it does. – Joe C Oct 22 '17 at 12:53
  • @JoeC Thanks, let me clarify it more clearly in the question. – Eugene Oct 22 '17 at 13:02
  • It's best when you need thread safety for a relatively small list, when you have a low update rate. – Peter Lawrey Oct 22 '17 at 13:09

1 Answers1

3

Based on the javadoc,

A thread-safe variant of java.util.ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

As you can see, any modification to the container is costly especially when the size of data in the container is big.

It's better to use CopyOnWriteArrayList when the frequency of modification is low. As suggested by JCIP,

the copy-on-write collections are reasonable to use only when iteration is far more common than modification.

For example the event-notification system. It will iterate the container every time an event needs to be notified but will only be modified when the observer is changed. The occurrence of the former is with high frequency and the latter is with low frequency.

Eugene
  • 10,627
  • 5
  • 49
  • 67