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:
Importance of Thread Synchronization in Java
Next article icon

Synchronization of ArrayList in Java

Last Updated : 03 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Implementation of ArrayList is not synchronized by default. It means if a thread modifies it structurally and multiple threads access it concurrently, it must be synchronized externally. Structural modification implies the addition or deletion of element(s) from the list or explicitly resizes the backing array. Changing the value of an existing element is not a structural modification.

There are two ways to create a Synchronized ArrayList. 

1. Collections.synchronizedList() method. 
2. Using CopyOnWriteArrayList.

Method 1: Using Collections.synchronizedList() method

To do serial access, all access to the backing list must be accomplished through the returned list. It is imperative that the user manually synchronizes on the returned list when iterating over it. 

public static  List<T> synchronizedList(List<T> list)
  • Accepts a List which could be the implementation of the List interface. e.g. ArrayList, LinkedList.
  • Returns a Synchronized(thread-safe) list backed by the specified list.
  • The parameter list is the list to be wrapped in a synchronized list.
  • T represents generic

Java




// Java program to demonstrate working of
// Collections.synchronizedList
 
import java.util.*;
 
class GFG
{
    public static void main (String[] args)
    {
        List<String> list =
           Collections.synchronizedList(new ArrayList<String>());
 
        list.add("practice");
        list.add("code");
        list.add("quiz");
 
        synchronized(list)
        {
            // must be in synchronized block
            Iterator it = list.iterator();
 
            while (it.hasNext())
                System.out.println(it.next());
        }
    }
}
 
 
Output
practice code quiz

Method 2: Using CopyOnWriteArrayList

CopyOnWriteArrayList<T> threadSafeList = new CopyOnWriteArrayList<T>();
  • Create an empty List.
  • It implements List interface.
  • It is a thread-safe variant of ArrayList.
  • T represents generic

A thread-safe variant of ArrayList in which all mutative operations (e.g., add, set, remove..) are implemented by creating a separate copy of an underlying array. It achieves thread safety by creating a separate copy of the List which is different than vector or other collections used to provide thread-safety. 

  • It is useful when you can’t or don’t want to synchronize the traversal yet need to prevent interference among concurrent threads.
  • It is costly as it involves separate Array copy with every write operation(e.g., add, set, remove.)
  • It is very efficient when you have List and need to traverse its elements and don’t modify it often.

The iterator does not throw ConcurrentModificationException even if copyOnWriteArrayList is modified once the iterator is created. The iterator is iterating over the separate copy of ArrayList while a write operation is happening on another copy of ArrayList.

Java




// Java program to illustrate the thread-safe ArrayList.
 
import java.io.*;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
 
class GFG
{
    public static void main (String[] args)
    {
        // creating a thread-safe Arraylist.
        CopyOnWriteArrayList<String> threadSafeList
            = new CopyOnWriteArrayList<String>();
 
        // Adding elements to synchronized ArrayList
        threadSafeList.add("geek");
        threadSafeList.add("code");
        threadSafeList.add("practice");
 
        System.out.println("Elements of synchronized ArrayList :");
 
        // Iterating on the synchronized ArrayList using iterator.
        Iterator<String> it = threadSafeList.iterator();
 
        while (it.hasNext())
            System.out.println(it.next());
    }
}
 
 
Output
Elements of synchronized ArrayList : geek code practice

What happens if we try to modify CopyOnWriteArrayList through the iterator’s method? 

It throws UnsupportedOperationException if you try to modify CopyOnWriteArrayList through iterator’s own method(e.g. add(), set(), remove()). 

Java




// Java program to illustrate the thread-safe ArrayList
 
import java.io.*;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
 
class GFG
{
    public static void main (String[] args)
    {
        // creating a thread-safe Arraylist.
        CopyOnWriteArrayList<String> threadSafeList =
            new CopyOnWriteArrayList<String>();
 
        // Adding elements to synchronized ArrayList
        threadSafeList.add("geek");
        threadSafeList.add("code");
        threadSafeList.add("practice");
 
        System.out.println("Elements of synchronized ArrayList :");
 
        // Iterating on the synchronized ArrayList using iterator.
        Iterator<String> it = threadSafeList.iterator();
 
        while (it.hasNext())
        {
            String str = it.next();
            it.remove();
        }
    }
}
 
 

Runtime Error: 

Exception in thread "main" java.lang.UnsupportedOperationException     at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove         (CopyOnWriteArrayList.java:1176)     at GFG.main(File.java:28)

Other constructors of CopyOnWriteArrayList 

1. CopyOnWriteArrayList(Collection<? extends E> c): Creates a list containing the elements of the specified collection, in the order, they are returned by the collection’s iterator. 

2. CopyOnWriteArrayList(E[] toCopyIn): Creates a list holding a copy of the given array.

Why use ArrayList when the vector is synchronized?

  1. Performance: Vector is synchronized and thread-safe, and because of this, it is slightly slower than ArrayList.
  2. Functionality: Vector synchronizes at the level of each individual operation. Generally, a programmer likes to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe and slower.
  3. Vectors obsolete: Vectors are considered obsolete and unofficially deprecated in java. Also, the vector synchronizes on each individual operation which is almost never done. Mostly java programmers prefer using ArrayList since they will probably synchronize the arrayList explicitly anyway if they need to synchronize.

Must Read: Vector vs ArrayList in Java



Next Article
Importance of Thread Synchronization in Java

N

Nitsdheerendra
Improve
Article Tags :
  • Java
  • Java-ArrayList
  • Java-Collections
  • Java-List-Programs
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • Static Synchronization in Java
    Synchronization is the potential to regulate the access of multiple threads to any shared resource. Synchronization in Java is essential for reliable communication between threads. It is achieved in Java with the use of synchronized keywords. Important Points Regarding Synchronization It is only for
    5 min read
  • Importance of Thread Synchronization in Java
    Thread synchronization in Java is important for managing shared resources in a multithreaded environment. It ensures that only one thread can access a shared resource at a time, which enhances the overall system performance and prevents race conditions and data corruption. Why is Thread Synchronizat
    8 min read
  • Join two ArrayLists in Java
    Given two ArrayLists in Java, the task is to join these ArrayLists. Examples: Input: ArrayList1: [Geeks, For, ForGeeks] , ArrayList2: [GeeksForGeeks, A computer portal] Output: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Input: ArrayList1: [G, e, e, k, s] , ArrayList2: [F, o, r, G, e, e
    1 min read
  • Java Method and Block Synchronization
    In Java, Synchronization is very important in concurrent programming when multiple threads need to access shared resources. Java Synchronization can be applied to methods and blocks. Method synchronization in Java locks the entire method and Block synchronization locks only a specific section of the
    7 min read
  • Vector vs ArrayList in Java
    ArrayList and Vectors both implement the List interface, and both use (dynamically resizable) arrays for their internal data structure, much like using an ordinary array. Syntax: ArrayList: ArrayList<T> al = new ArrayList<T>(); Vector: Vector<T> v = new Vector<T>(); ArrayList
    4 min read
  • Internal Working of ArrayList in Java
    ArrayList is a resizable array implementation in Java. ArrayList grows dynamically and ensures that there is always a space to add elements. The backing data structure of ArrayList is an array of Object classes. ArrayList class in Java has 3 constructors. It has its own version of readObject and wri
    10 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
  • ArrayList vs LinkedList in Java
    An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the diff
    5 min read
  • Java ArrayList retainAll() Method
    The retainAll() method of ArrayList class in Java is used to retain only the elements in the list that are contained in the specified collection. It removes all elements from the list that are not in the specified collection. Example 1: Passing an ArrayList as the Parameter In this example, we pass
    4 min read
  • Java notify() Method in Threads Synchronization with Examples
    The notify() method is defined in the Object class, which is Java's top-level class. It's used to wake up only one thread that's waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread. If multiple threads are waiting for noti
    3 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