• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

How to Synchronize ArrayList in Java

August 31, 2023 //  by Talha Malik

In Java, there are various containers to store data. The “ArrayList” is one such container that is not thread-safe. This implies that it is not a good practice to utilize it in a multithreading environment without appropriate synchronization. This procedure avoids retrieving undesirable or garbage outputs and ensures proper resource utilization.

This write-up will demonstrate how to synchronize the ArrayList in Java.

What is Synchronization in Java?

“Synchronization” in Java corresponds to the procedure of enabling/allowing only one thread at a time to conclude the task. It enables only one thread to invoke a single resource/ task.

How to Synchronize the Java ArrayList?

This synchronization of ArrayList can be done using the below-given approaches:

  • “Collections.synchronizedList()” Method. 
  • “CopyOnWriteArrayList”.

Approach 1: Synchronize ArrayList Using the “Collections.synchronizedList()” Method

This method is utilized to synchronize collections in Java.

Syntax

public static List<T> synchronizedList(List<T> list)

In this syntax, “T” indicates the data type of the list, and the “synchronizedList()” method takes List which refers to the implementation of the List interface i.e., ArrayList, LinkedList, etc.

Now, proceed to the practical implementation of the discussed method:

import java.util.*;
public class Synchronizedlist {
public static void main (String[] args){
  List<String> x = Collections.synchronizedList(new ArrayList<String>());
  x.add("Java");
  x.add("Programming");
  x.add("Language");
  synchronized(x){
  Iterator y = x.iterator();
  while (y.hasNext())
  System.out.println(y.next());
}}
}

According to this block of code:

  • Create an ArrayList of the “String” type and apply the “Collections.synchronizedList()” method on it for synchronizing the list.
  • In the next step, append the specified string values to the list utilizing the “add()” method.
  • Now, use the synchronized block to refrain from the non-deterministic behavior.
  • In this block, iterate the ArrayList via the Iterator “hasNext()” and “next()” methods, respectively.

Output

This outcome implies that the ArrayList elements are iterated appropriately.

Let’s take another code where the “ConcurrentModificationException” will be encountered by appending a number into the synchronized list while the iteration is being done:

import java.util.*;
public class Synchronizedlist {
public static void main(String[] args) {
  ArrayList<Integer> x = new ArrayList<Integer>();
  for(int i = 0; i < 5; i++) {
  x.add(i);
}
  List<Integer> z = Collections.synchronizedList(x);
  synchronized(z) {
  Iterator<Integer> y = z.iterator();
  while(y.hasNext()) {
    x.add(8);
    System.out.println(y.next());
}}
}}

In this code, the “for” loop is applied to insert the values in the ArrayList and the list is synchronized. After that, the stated integer is added to the list, thereby modifying it while iteration that returns the “ConcurrentModificationException” limitation.

Output

Approach 2: Synchronize ArrayList Using “CopyOnWriteArrayList”

The “CopyOnWriteArrayList” implements the List interface and creates a null list. Also, it defines a list of the items in the order of the provided collection. 

Syntax

CopyOnWriteArrayList<T> x= new CopyOnWriteArrayList<T>();

According to this syntax, “T” corresponds to the datatype of the list.

Now, overview the below-given code snippet that synchronizes the ArrayList via the discussed approach:

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Synchronizedlist {
public static void main (String[] args){
  CopyOnWriteArrayList<String> x = new CopyOnWriteArrayList<String>();
  x.add("Java");
  x.add("Programming");
  x.add("Language");
  Iterator<String> y = x.iterator();
  while (y.hasNext())
  System.out.println(y.next());
}}

In these lines of code:

  • Create a “CopyOnWriteArrayList” object of the “String” type that creates a thread-safe ArrayList.
  • After that, add the given string values in it via the “add()” method.
  • Now, similarly, iterate the ArrayList using the Iterator methods.

Output

“CopyOnWriteArrayList” Constructors

Following are the other constructors of “CopyOnWriteArrayList”:

CopyOnWriteArrayList(Collection<? extends E> c): It creates a list comprising the items of the target collection, in the order they are retrieved by the collection’s iterator. 

CopyOnWriteArrayList(E[] toCopyIn): This constructor creates a list containing a copy of the provided array.

Modifying “CopyOnWriteArrayList” Via the iterator’s Method

This approach returns the “UnsupportedOperationException” limitation if the modification is done on “CopyOnWriteArrayList” via the iterator’s own method i.e., add(), set(), demonstrated below: 

As analyzed, the discussed exception is thrown.

However, the iterator does not return the “ConcurrentModificationException” even if “copyOnWriteArrayList” is modified during the iteration, demonstrated as follows:

Conclusion

An ArrayList in Java can be synchronized using the “Collections.synchronizedList()” method, or via “CopyOnWriteArrayList”. The former approach throws the “ConcurrentModificationException” during iteration whereas it is not the case in the latter approach. This article demonstrated the procedures to synchronize the Java ArrayList.

Category: Java

Previous Post: « How to Resolve the “int cannot be dereferenced” Error in Java
Next Post: How to Use ConcurrentLinkedQueue in Java with Examples »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Use Optional.ofNullable() Method in Java

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact