Describe CopyOnWriteArrayList? Where is it used in Java Applications?

By | August 13, 2019

In this blog post we will discuss about one of the very important java interview question Describe CopyOnWriteArrayList? Where is it used in Java Applications? We will  look into some practical examples so that below points would me clear to you about CopyOnWriteArrayList.

  • Functionality wise this collection is very much similar to ArrayList except the fact that CopyOnWriteArrayList is thread-safe.
  • It maintains thread-safety using Immutability approach, where any modification operations results in creating a fresh copy of the underlying array.
  • Using CopyOnWriteArrayList is too costly but may be more efficient than alternatives when traversal operations vastly with updating and is useful when you don’t want to use synchronize traversals.
  • CopyOnWriteArrayList creates the “snapshot” style iterator and uses a reference to the state of the array at the point that the iterator was created. Underlying array of  CopyOnWriteArrayList never changes during the entire lifetime of the iterator and that’s way interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.
  • Element-changing operations in CopyOnWriteArrayList using iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.

Example which will throw ConcurrentModificationException known as Fail-Fast Iterators

Above program will throw Exception as below:

Example which will  not throw ConcurrentModificationException known as Fail-Safe Iterators

 Above program will produce below output without any Exception:

You may also like:

What are common multi-threading issues faced by Java Developers?
What are different states of a Thread? What does those states tell us?
What happens when wait() & notify() methods are called?
What is difference between sleep(), yield() and wait() method?
What is difference between Callable and Runnable Interface?

That’s all about  Describe CopyOnWriteArrayList? Where is it used in Java Applications?
If you have any feedback or suggestion please feel free to drop in blow comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *