How to synchronize ArrayList in java with example

We all know that  ArrayList class is non-synchronized and should not be used in multi-thread environment without explicit synchronization. In this article we will learn how to synchronize ArrayList in Java. We will be following two approaches here

  1. Using Collections.synchronizedList() method
  2. Using CopyOnWriteArrayList (thread-safe variant of ArrayList)

1. Using Collections.synchronizedList() method

In this approach we will be passing the tempList(Non Synchronized List) to Collections.synchronizedList() method to get a synchronized list. Point to be noted is that while iterating over the syncList the iterator should be inside a synchronized block to prevent non-deterministic behavior of the list.

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class SynchronizeArrayListExample 
{
    public static void main(String arg[])
    {
        List<String> tempList = new ArrayList<String>();
        
        //Adding elements to tempList using add() method
        tempList.add("Val1");
        tempList.add("Val3");
        tempList.add("Val2");
        tempList.add("Val4");
        
        //Synchronize tempList using Collections.synchronizedList() method
        List<String> syncList = Collections.synchronizedList(tempList);
        
        System.out.println("Iterating the Synchronized List");
        synchronized (syncList) 
        {
            Iterator it = syncList.iterator();
            while(it.hasNext())
            {
                System.out.println(it.next());
            }
        }
    }
}

Output :

Iterating the Synchronized List
Val1
Val3
Val2
Val4

2. Using CopyOnWriteArrayList

CopyOnWriteArrayList implements List interface like ArrayList, Vector and LinkedList but its a thread-safe collection.

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

public class SynchronizeArrayListExample 
{
    public static void main(String arg[])
    {
        CopyOnWriteArrayList syncList = new CopyOnWriteArrayList();
        
        //Adding elements to tempList using add() method
        syncList.add("Val1");
        syncList.add("Val3");
        syncList.add("Val2");
        syncList.add("Val4");
        
        System.out.println("Iterating the Synchronized List");
        //Synchronized block is not required here
        Iterator it = syncList.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }
}

Output :

Iterating the Synchronized List
Val1
Val3
Val2
Val4

Leave a Reply

Your email address will not be published. Required fields are marked *