Since ArrayList is non-synchronized and should not be used in multithreaded environment without explicit synchronization.In this tutorial we will learn about how to synchronize ArrayList in java.
Method 1 : Using Collections.synchronizedList()
One liner is using Collections.synchronizedList() we can make ArrayList synchronized.
import java.util.*; public class SynchronizedArrayList { public static void main(String args[]) { // Converting ArrayList to Synchronized ArrayList List<String> synchronizedarraylist = Collections.synchronizedList(new ArrayList<String>()); //Adding elements to synchronized ArrayList synchronizedarraylist.add("Basketball"); synchronizedarraylist.add("Baseball"); synchronizedarraylist.add("Football"); System.out.println("Synchronized ArrayList Iteration:"); synchronized(synchronizedarraylist) { Iterator<String> iterator = synchronizedarraylist.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } } }
Output
Synchronized ArrayList Iteration: Basketball Baseball Football
Method 2 :Using CopyOnWriteArrayList
import java.util.*; import java.util.concurrent.*; public class SynchronizedArrayList { public static void main(String args[]) { // Creating Synchronized ArrayList Object CopyOnWriteArrayList<String> al = new CopyOnWriteArrayList<String>(); //Adding elements to synchronized ArrayList al.add("Basketball"); al.add("Baseball"); al.add("Football"); System.out.println("Showing synchronized ArrayList Elements:"); //Synchronized block is not required in this method Iterator<String> iterator = al.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } }
Output
Showing synchronized ArrayList Elements: Basketball Baseball Football