Tag Archives: copyonwritearraylist vs synchronized arraylist

How CopyOnWriteArrayList works in Java how it differ from ArrayList

In this article, we will see one of the most important concurrent collection class CopyOnWriteArrayList and we also look into the working of CopyOnWriteArrayList class including its comparison with ArrayList and in which situation CopyOnWriteArrayList should be preferred over ArrayList.

Few Drawbacks of ArrayList

  • If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.Means whenever there is access or modification we need synchronization that is a overhead.
  • The iterator will throw a ConcurrentModificationException

What is copy-on-write concept
Copy-on-write is an optimization strategy used in computer programming. Copy-on-write stems from the understanding that when multiple separate tasks use identical copies of the same information, it is not necessary to create separate copies of that information for each process, instead they can all be given pointers to the same resource. When there are many separate processes all using the same resource it is possible to make significant resource savings by sharing resources this way. However, when a local copy has been modified, the copy-on-write paradigm has no provision that the shared resource has in the meantime not been updated by another task or tasks.
So Copy-on-write is therefore only suggested if only the latest update is important and occasional use of a slightly stale value is not harmful. Copy-on-write is the name given to the process of identifying when a task attempts to make a change to the shared information, creating a separate (private) copy of that information for the task and redirecting the task to making changes to the private copy to prevent its changes from becoming visible to all the other tasks

Click here to read more

Advertisements