Get Synchronized List from ArrayList in java

Java 8Object Oriented ProgrammingProgramming

In order to get a synchronized list from an ArrayList, we use the synchronizedList(List <T>) method in Java. The Collections.synchronizedList(List <T>) method accepts the ArrayList as an argument and returns a thread safe list.

Declaration −The Collections.synchronizedList(List <T>) method is declared as follows −

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

Let us see a program to get a synchronized List from ArrayList −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      List<String> list = new ArrayList<String>();
      list.add("Hello");
      list.add("Hi");
      list.add("World");
      list = Collections.synchronizedList(list);
      synchronized(list) {
         Iterator itr = list.iterator();
         while (itr.hasNext())
         System.out.print(itr.next()+" ");
      }
   }
}

Output

Hello Hi World
raja
Published on 08-Jan-2019 12:44:23
Advertisements