Here we are going to share two common as well as efficient ways to synchronize ArrayList in Java.

Using Collections.synchronizedList():

The Collections.synchronizedList() method returns a thread-safe ArrayList backed by a specific list.

Source code:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;


public class SyncronizeArrayList {
    
    public static void main(String[] args) {
        
        List languageList = new ArrayList<>(Arrays.asList("Java", "Python", "HTML", "CSS"));
        // Synchronizing ArrayList in Java  
        languageList = Collections.synchronizedList(languageList);  
  
        // we must use synchronize block to avoid non-deterministic behavior  
        synchronized (languageList) {  
            Iterator iterator = languageList.iterator();  
            while (iterator.hasNext()) {  
                System.out.println(iterator.next());  
            }  
        }  
    }
}

Output:

run:
Java
Python
HTML
CSS
BUILD SUCCESSFUL (total time: 12 seconds)

Initializing thread-safe list:

Rather than synchronizing an ArrayList, you can also declare or initialize a thread-safe list.

Source code:

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


public class SyncronizeArrayList {

    public static void main(String[] args) {
        // Initializing a thread-safe Arraylist.
        CopyOnWriteArrayList list = 
                           new CopyOnWriteArrayList(Arrays.asList("John", "Sara", "Ali", "Sam"));

        System.out.println("Following are elements of synchronized ArrayList: ");

        // Using iterator for Iterating on the synchronized ArrayList.
        Iterator itr = list.iterator();

        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Output:

run:
Following are elements of synchronized ArrayList: 
John
Sara
Ali
Sam
BUILD SUCCESSFUL (total time: 2 seconds)

References:

One Comment

  1. Manisha November 26, 2021 at 3:17 pm - Reply

    Thanks for writing this article.

Leave A Comment