Home >Java >javaTutorial >How many ways can I synchronize an ArrayList in Java?
ArrayList is a subclass of the AbstractList class, which can be used to store elements of a dynamically sized collection . ArrayList increases its size to accommodate new elements and shrinks in size when elements are removed, hence the name Resizable or dynamic array. ArrayList can allow duplicate values and null values .
There are two methods to synchronize ArrayList in Java
synchronizedList() method is used to synchronize collections in Java .
public static List<T> synchronizedList(List<T> list)
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.<strong>synchronizedList</strong>(list); <strong>synchronized</strong>(synlist) { Iterator<String> itr = synlist.iterator(); while(itr.hasNext()) { String str = itr.next(); System.out.println(str); } } } }
IND AUS WI NZ ENG
CopyOnWriteArrayList Will create a list of elements in the specified collection order. It is thread-safe for ArrayList with concurrent access. When an ArrayList is modified, it creates a new copy of the underlying array.
public class CopyOnWriteArrayList<E> extends Object implements List<E>, RandomAccess, Cloneable, Serializable
import java.util.*; import java.util.concurrent.*; public class CopyOnWriteArrayListTest { public static void main(String[] args) { <strong>CopyOnWriteArrayList </strong>list = new <strong>CopyOnWriteArrayList</strong>(); 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); } } }
Displaying synchronized ArrayList: Java Scala Python Selenium ServiceNow
The above is the detailed content of How many ways can I synchronize an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!