The Wayback Machine - https://web.archive.org/web/20241117212440/https://www.geeksforgeeks.org/difference-between-synchronized-arraylist-and-copyonwritearraylist-in-java-collection/
Open In App

Difference Between Synchronized ArrayList and CopyOnWriteArrayList in Java Collection

Last Updated : 15 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

As we know that the ArrayList is not synchronized, if multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. Hence synchronizing the ArrayList is a must to achieve thread safety in a multi-threaded environment.

In order to make List objects we were generally creating objects of the List interface and there making List classes as per our requirements and lately adding elements and were accessing, updating without having a thought about thread safety. This concept is easy and at the same time, a bit advanced because it is seen most Java developers do not practice this technique while writing codes. 

Note: Synchronized ArrayList is synchronized collection while CopyOnWriteArrayList is an concurrent collection as it is made with keeping concurrency.

Different Ways of Achieving Synchronization in ArrayList 

Synchronization in an Arraylist can be achieved in two ways: 

  1. Using synchronizedList() Method of Collections Class
  2. Using CopyOnWriteArrayList (COWAL)

Example

Java




// Java Program to Illustrate Synchronized ArrayList
// Using synchronizedList() Method
 
// Importing required classes
import java.util.* ;
 
// Main class
// SynchronizedArrayList
class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Creating an empty ArrayList of string type
        // By default, non - synchronized List
        List<String> sal = new ArrayList<String>();
 
        // Adding elements to above List
        // using add() method
        sal.add("Geeks");
        sal.add("for");
        sal.add("Geeks");
        sal.add("Computer");
        sal.add("Science");
        sal.add("Portal");
 
        // Printing the above non-synchronised List
        System.out.println(sal);
 
        // Synchronizing above List
        // using SynchronizedList() method
        Collections.synchronizedList(sal);
 
        // Synchronized block to
        // avoid non-deterministic behavior
        synchronized (sal) {
 
            // Using iterators to iterate over elements
            Iterator<String> itrobj = sal.iterator();
 
            // Holds true till there is single element remaining
            while (itrobj.hasNext()) {
                // Printing elements
                // using next() method
                System.out.println(itrobj.next());
            }
        }
    }
}


Output:

Since both ways are used to achieve thread-safety in Arraylist. The question appears, when to use COWAL and when to use synchronizedList() method of Collections class. This can be understood by understanding the differences between them. The main difference between synchronized ArrayList and CopyOnWriteArrayList comes from their performance, scalability, and how they achieve thread safety. 

Why CopyOnWriteArrayList came into existence when Collection.synchronizedList() was already present?

So the answer is pretty simple because initially, SynchronizedList was used in a multithreaded environment but it had some limitations. All of its read and write methods were synchronized on the list object itself, i.e. if a thread is executing add() method, it blocks other threads which want to get the iterator to access elements in the list. Also, only one thread was allowed to iterate the list’s elements at a time, which was inefficient. That was quite rigid. Thus a more flexible collection was required which allows: 

  1. Multiple threads executing read operations concurrently.
  2. One thread executes the read operation and another executes the write operation concurrently.
  3. Only one thread can execute write operations while other threads can execute read operations simultaneously.

To overcome these issues, finally, in Java 5, a new set of collection classes called Concurrent Collections was introduced which had CopyOnWriteArrayList in it. The CopyOnWriteArrayList class is designed to enable such sequential write and concurrent reads features. 

Let us discuss characteristics associated with both of them that create a thin line of difference between them that are as listed below:  

1. Locking of Threads

Synchronized List locks the whole list to provide synchronization and thread safety during the read or write operation, while, CopyOnWriteArrayList doesn’t lock the whole list during these operations. 
The CopyOnWriteArrayList class works according to its name i.e. copy-on-write which performs different actions for reading and write operations. For every write operation (add, set, remove, etc), it makes a new copy of the elements in the list. and for the read operations (get, iterator, listIterator, etc), it works on a different copy. So there is no additional overhead during a read operation and its read operation is faster than Collections.SynchronizedList(). Thus, COWAL is better for reading operation than Synchronized List. 

2. Write Operations

For write operation in ArrayList, COWAL write operations are slower than Collections.synchronizedList(), since it uses Re-entrantLock. The write method will always create a copy of the existing array and do the modification on the copy and then finally update the volatile reference of the array to point to this new array. Therefore, it has massive overhead during a write operation. That’s why CopyOnWriteArrayList write operations are slower than Collections.synchronizedList().

3. Behavior During Modification

Synchronized List is a fail-fast iterator, i.e. it will throw ConcurrentModifcationException when the list is modified when one thread is iterating over it whereas CopyOnWriteArrayList is a fail-safe iterator, i.e. it will not throw ConcurrentModifcationException even when the list is modified when one thread is iterating over it.

4. Number of Threads Working

Only one thread is allowed to operate on Synchronized List, by locking over the complete list object which affects its performance since other threads are waiting whereas, in the case of COWAL, multiple threads are allowed to operate on ArrayList, as it works on separate cloned copy for update/modify operations which makes its performance faster.

5. Iterating within Block

While iterating synchronized List, make sure to iterate inside the synchronized block whereas, in CopyOnWriteArrayList, we can safely iterate outside the synchronized block.

When to use SynchronizedList?

  • Since in CopyOnWriteArrayList for every update/modify operation, a new separate cloned copy is created and there is overhead on JVM to allocate memory and merge cloned copy with the original copy. Thus, in this case, SynchronizedList is a better option.When the size of Arraylist is large.
  • When size of Arraylist is large.

When to use CopyOnWriteArrayList?

  • The CopyOnWriteArrayList provides reading without a lock, which means a much better performance if there are more reader threads and writing is happening quite low.
  • When the size of Arraylist is small.

SynchronizedList v/s CopyOnWriteArrayList

SynchronizedArrayList  CopyOnWriteArrayList 
It was introduced in Java version 1.2 It was introduced in Java version 1.5
It should be used when there are more write operations over-read operations. It should be used when there are more read operations than write operations.
The iterator used is fail-fast. The iterator used is fail-safe.
The iteration of List has to be there inside the synchronized block.   The iteration of the list can be outside the synchronized block.
The whole ArrayList is locked by Synchronized Arraylist for thread safety during read and write operations.  The whole ArrayList is locked by SynchronizedArrayList for thread safety during the write operations only.
It is preferred when ArrayList is larger. It is preferred when ArrayList is smaller. 


Previous Article
Next Article

Similar Reads

ArrayList of ArrayList in Java
We have discussed that an array of ArrayList is not possible without warning. A better idea is to use ArrayList of ArrayList. // Java code to demonstrate the concept of // array of ArrayList import java.util.*; public class Arraylist { public static void main(String[] args) { int n = 3; // Here aList is an ArrayList of ArrayLists ArrayList<Array
1 min read
Difference between Arrays and Collection in Java
An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. On the other hand, any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate frame
3 min read
Java.util.ArrayList.add() Method in Java
Below are the add() methods of ArrayList in Java: boolean add(Object o) : This method appends the specified element to the end of this list. Parameters: object o: The element to be appended to this list. Exception: NA // Java code to illustrate add(Object o) import java.io.*; import java.util.ArrayList; public class ArrayListDemo { public static vo
2 min read
Graph Representation using Java ArrayList
Prerequisite : Graph and its representations In this article, we will be discussing Adjacency List representation of Graph using ArrayList in Java. Following is adjacency list representation of the above graph. The idea is to use ArrayList of ArrayLists. // Java code to demonstrate Graph representation // using ArrayList in Java import java.util.*;
2 min read
Custom ArrayList in Java
Before proceeding further let us quickly revise the concept of the arrays and ArrayList quickly. So in java, we have seen arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework. Being a good programmer one is already
8 min read
Difference between YAML(.yml) and .properties file in Java SpringBoot
These are the files to have different configurations properties required to make the application up and run like to connect with the database what are the credentials, on which port the application will run, etc. YAML (.yml) File: YAML is a configuration language. Languages like Python, Ruby, Java heavily use it for configuring the various properti
3 min read
Difference between Simple and Compound Assignment in Java
Many programmers believe that the statement "x += i" is simply a shorthand for "x = x + i". This isn’t quite true. Both of these statements are assignment expressions. The second statement uses the simple assignment operator (=), whereas the first uses a compound assignment operator. The compound assignment operators are +=, -=, *=, /=, %= etc. The
2 min read
Difference between Method and Function in Python
Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method definition always includes 'self' as its first para
3 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Difference between Procedural and Declarative Knowledge
Procedural Knowledge: Procedural Knowledge also known as Interpretive knowledge, is the type of knowledge in which it clarifies how a particular thing can be accomplished. It is not so popular because it is generally not used. It emphasize how to do something to solve a given problem. Let's see it with an example: var a=[1, 2, 3, 4, 5]; var b=[]; f
2 min read
Difference between SMS and MMS
We always send messages to others. In older days people have only one means of communication i.e, letters but nowadays there are many ways to send messages like email, SMS, MMS, and messages on the OTT (over-the-top) application like WhatsApp, telegram, and signal. The two main ways to send messages on the mobile phone using a cellular network are
3 min read
Difference between the Constructors and Methods
Java is a pure OOPS concept based programming language. Hence in Java, all the variables, data and the statements must be present in classes. These classes consist of both constructors and methods. Methods and Constructors are different from each other in a lot of ways. Constructors: Constructors are used to initialize the object's state. Like meth
3 min read
Difference between Management Information System (MIS) and Decision Support System (DSS)
Decision Support System (DSS) is an interactive, flexible computer based information system or sub-system intended to help decision makers use communication technologies, data, documents to identify and solve problems, complete decision process tasks and make decision. Management Information System (MIS) consists of following three pillars: Managem
2 min read
Difference between Fuzzification and Defuzzification
Fuzzification: It is the method of transforming a crisp quantity(set) into a fuzzy quantity(set). This can be achieved by identifying the various known crisp and deterministic quantities as completely nondeterministic and quite uncertain in nature. This uncertainty may have emerged because of vagueness and imprecision which then lead the variables
2 min read
Difference between Optical Character Recognition (OCR) and Magnetic Ink Character Reader (MICR)
Optical Character Recognition (OCR): OCR is the mechanical-electronic that converts the images into machine-encoded text. In other words, it is the use of technology to distinguish printed or handwritten text characters inside digital images of physical documents, such as scanned paper documents. Difference between Optical Character Recognition (OC
2 min read
Difference between Information and Knowledge
Information: Information is delineate because the structured, organized and processed data, conferred inside context, that makes it relevant and helpful to the one who desires it. Data suggests that raw facts and figures regarding individuals, places, or the other issue, that is expressed within the type of numbers, letters or symbols. Information
2 min read
Difference between Function and Procedure
Pre-requisites: What is SQL? Structured Query Language is a computer language that we use to interact with a relational database.SQL is a tool for organizing, managing, and retrieving archived data from a computer database. In this article, we will see the difference between Function and Procedure. Function:The function is one of the fundamental th
3 min read
Difference between LED and LCD
Light Emitting Diode (LED): LED is a type of LCD that actually accompanies the advancement of technology. This replaces the fluorescent tube with backlight technology, which produces a clearer picture than the LCD. LED have wider viewing angle than the LCD. It have better black level and contrast in comparison to LCD LCD display. LED delivers bette
2 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
Difference between Open-Loop Control System and Closed-Loop Control System
Control System is a system in which the behavior of the system is determined by a differential equation. It manages the devices and the systems using control loops. There are Open-Loop Control System and Closed-Loop Control System. Open-Loop Control System is used in applications in which no feedback and error handling are required. It is simple an
3 min read
Difference Between Apache Hadoop and Amazon Redshift
Hadoop is an open-source software framework built on the cluster of machines. It is used for distributed storage and distributed processing for very large data sets i.e. Big Data. It is done using the Map-Reduce programming model. Implemented in Java, a development-friendly tool backs the Big Data Application. It easily processes voluminous volumes
3 min read
Difference Between Hive Internal and External Tables
Hive can be used to manage structured data on the top of Hadoop. The data is stored in the form of a table inside a database. In Hive, the user is allowed to create Internal as well as External tables to manage and store data in a database. In this article, we will be discussing the difference between Hive Internal and external tables with proper p
6 min read
Absolute difference between the count of odd and even factors of N
Given a positive integer N, the task is to find the absolute difference of the count of odd and even factors of N. Examples: Input: N = 12Output: 2Explanation: The even factors of 12 are {2, 4, 6, 12}. Therefore, the count is 4.The odd factors of 12 are {1, 3}. Therefore, the count is 2.Hence, the difference between their counts is (4 - 2) = 2. Inp
13 min read
Difference between #include and #include" " in C/C++ with Examples
Pre-requisites: Header files in C/ C++ and its uses The difference between the two types is in the location where the preprocessor searches for the file to be included in the code. #include <filename> // Standard library header #include "filename" // User defined header #include<filename> #include<> is for pre-defined header files
4 min read
Power BI - Difference between SUM() and SUMX()
Recognizing that Power BI has two fundamental computation engines will help you move forward. An iterator engine and an aggregator engine both exist. The distinction between SUM and SUMX in Power BI is still very unclear. Both functions can be utilized in various contexts, but there are some situations when one is more effective than the other, thu
6 min read
Difference Between Structure and Union in C
Structures in C is a user-defined data type available in C that allows to combining of data items of different kinds. Structures are used to represent a record. Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than or equal to one member. The format of the struct
4 min read
Difference between sums of odd and even digits
Given a long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for leftmost digit). Examples: Input: 1212112Output: YesExplanation:the odd position element is 2+2+1=5the even position element is 1+1+1+2=5the difference is 5-5=0 equal to zero. So print yes
3 min read
Difference between np.asarray() and np.array()?
NumPy is a Python library used for dealing with arrays. In Python, we use the list inplace of the array but it’s slow to process. NumPy array is a powerful N-dimensional array object and is used in linear algebra, Fourier transform, and random number capabilities. It provides an array object much faster than traditional Python lists. np.array in Py
3 min read
Difference between Laptop and Notebook
1. Laptop: The laptop is a modern computer and an alternative to the desktop computer. Laptops are portable and have the same power as desktop computers and can be used according to the user. Laptops typically weigh between 4 and 12 pounds, and display sizes and thickness vary depending on their models. Unlike notebooks, laptops have DVD-drive and
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg