How to synchronize ArrayList in Java

ArrayList is non-synchronized collection and should not be used in concurrent environment without explicit synchronization. To synchronize ArrayList, we can use two JDK provided methods.

  1. Collections.synchronizedList() method – It returns synchronized list backed by the specified list.
  2. CopyOnWriteArrayList class – It is a thread-safe variant of ArrayList.

1. Collections.synchronizedList() to synchronize ArrayList

This method returns a synchronized thread-safe list backed by the specified list. It is recommended that we should manually synchronize on the returned list when traversing it via Iterator, Spliterator or Stream. Else it may result in non-deterministic behavior.

No explicit synchronization is needed to add, remove elements from synchronized arraylist.

List<String> namesList = Collections.synchronizedList(new ArrayList<String>());

//List methods are synchronized

namesList.add("Alex");
namesList.add("Brian");

//Use explicit synchronization while iterating

synchronized(namesList) 
{
	Iterator<String> iterator = namesList.iterator(); 
	while (iterator.hasNext()) 
	{
		System.out.println(iterator.next());
	}
}

Program output.

Alex
Brian

2. CopyOnWriteArrayList which is implicit thread safe

CopyOnWriteArrayList is a thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array. This class is very useful when you cannot or don’t want to synchronize traversals of arraylist. It is part of thread safe Java collections.

This class uses “snapshot” style iterator method. It uses a reference to the state of the backing array at the point that the iterator was created. This array never changes during the lifetime of the iterator.

The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported.

CopyOnWriteArrayList<String> namesList = new CopyOnWriteArrayList<String>();

//List methods are synchronized

namesList.add("Alex");
namesList.add("Brian");

//No explicit synchronization is needed during iteration

Iterator<String> iterator = namesList.iterator(); 
while (iterator.hasNext()) 
{
	System.out.println(iterator.next());
}

Program output.

Alex
Brian

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.