Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to remove a SubList from a List in Java
Next article icon

Difference Between Synchronized ArrayList and CopyOnWriteArrayList in Java Collection

Last Updated : 15 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 


Next Article
How to remove a SubList from a List in Java

T

Tapan rawat
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • Java List Interface
    The List Interface in Java extends the Collection Interface and is a part of the java.util package. It is used to store the ordered collections of elements. In a Java List, we can organize and manage the data sequentially. Key Features: Maintained the order of elements in which they are added.Allows
    15+ min read
  • AbstractList in Java with Examples
    The AbstractList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. AbstractList class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a Rand
    8 min read
  • ArrayList in Java
    Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
    10 min read
  • LinkedList in Java
    Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and addr
    13 min read
  • Immutable List in Java
    ImmutableList, as suggested by the name, is a type of List which is immutable. It means that the content of the List are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the List, UnsupportedOperationException is thrown. An I
    5 min read
  • CopyOnWriteArrayList in Java
    CopyOnWriteArrayList class is introduced in JDK 1.5, which implements the List interface. It is an enhanced version of ArrayList in which all modifications (add, set, remove, etc) are implemented by making a fresh copy. It is found in java.util.concurrent package. It is a data structure created to b
    6 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
    8 min read
  • Difference Between Synchronized ArrayList and CopyOnWriteArrayList in Java Collection
    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
    6 min read
  • How to remove a SubList from a List in Java
    Given a list in Java, the task is to remove all the elements in the sublist whose index is between fromIndex, inclusive, and toIndex, exclusive. The range of the index is defined by the user. Example: Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4 Output [1, 2, 5, 6, 7, 8] Input
    2 min read
  • Randomly Select Items from a List in Java
    In this article, we will explore how to efficiently select an element from a list in Java. The basic approach involves generating a random index between 0 and the size of the list, and then using that index to retrieve the item. Different Ways to Select Items from a ListBelow are the different appro
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences