How many ways to synchronize an ArrayList in Java?

JavaObject Oriented ProgrammingProgramming

An ArrayList is a subclass of AbstractList class and it can be used to store a dynamically sized collection of elements. An ArrayList grows its size to accommodate new elements and shrinks the size when the elements are removed, so it is called resizable or dynamic array. An ArrayList can allow duplicates and null values.

There are two ways to synchronize an ArrayList in Java

Collections.synchronizedList() method

The synchronizedList() method is used to synchronize the collections in Java.

Syntax

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

Example

import java.util.*;
public class SynchronizedListTest {
   public static void main(String[] args) {
      List<String> list = new ArrayList<String>();
      list.add("IND");
      list.add("AUS");
      list.add("WI");
      list.add("NZ");
      list.add("ENG");
      List<String> synlist = Collections.synchronizedList(list);
      synchronized(synlist) {
         Iterator<String> itr = synlist.iterator();
         while(itr.hasNext()) {
            String str = itr.next();
            System.out.println(str);
         }
      }
   }
}

Output

IND
AUS
WI
NZ
ENG


CopyOnWriteArrayList

The CopyOnWriteArrayList will create a list of the elements in the order of specified collection. It is thread-safe concurrent access of ArrayList. When an ArrayList is modified, it will create a fresh copy of the underlying array.

Syntax

public class CopyOnWriteArrayList<E> extends Object implements List<E>, RandomAccess, Cloneable, Serializable

Example

import java.util.*;
import java.util.concurrent.*;
public class CopyOnWriteArrayListTest {
   public static void main(String[] args) {
      CopyOnWriteArrayList list = new CopyOnWriteArrayList();
      list.add("Java");
      list.add("Scala");
      list.add("Python");
      list.add("Selenium");
      list.add("ServiceNow");
      System.out.println("Displaying synchronized ArrayList: ");
      Iterator itr = list.iterator();
      while(itr.hasNext()) {
         String str = itr.next();
         System.out.println(str);
      }
   }
}

Output

Displaying synchronized ArrayList:
Java
Scala
Python
Selenium
ServiceNow
raja
Published on 29-Aug-2019 08:34:25
Advertisements