In this article, we will discuss how to get synchronized version of List using Collections class’s utility synchronizedList() method
Q) How to make Synchronized List ?
- From original collection framework introduced in Java 1.2 version, by default ArrayList/LinkedList classes aren’t thread-safe i.e.; non-synchronized
- But we can make it thread using Collections utility synchronizedList(list) method
- While iterating synchronized List, make sure to iterate inside synchronized block;
- otherwise we may face non-deterministic behavior
From Java doc,
* It is imperative that the user manually synchronize on the returned
* list when iterating over it:
List list = Collections.synchronizedList(new ArrayList()); ... synchronized (list) { Iterator i = list.iterator(); // Must be in synchronized block while (i.hasNext()) foo(i.next()); }
* Failure to follow this advice may result in non-deterministic behavior.
1. To get Synchronized version of ArrayList
Method signature:
public static List synchronizedList(List<Object> list);
SynchronizedVersionOfList.java
package in.bench.resources.java.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class SynchronizedVersionOfList {
public static void main(String[] args) {
// creating ArrayList object of type String
ArrayList<String> unSynchronizedList = new ArrayList<String>();
// adding elements to ArrayList object
unSynchronizedList.add("Facebook");
unSynchronizedList.add("LinkedIn");
unSynchronizedList.add("YouTube");
unSynchronizedList.add("Google");
// to get synchronized ArrayList
List<String> synchronizedList = Collections
.synchronizedList(unSynchronizedList);
System.out.println("Iterating through synchronized ArrayList\n");
// synchronized block
synchronized(synchronizedList) {
Iterator<String> iterator = synchronizedList.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
}
}
Output:
Iterating through synchronized ArrayList
Facebook
LinkedIn
YouTube
Google
Note: similarly, we can make thread-safe for LinkedList/Vector class
Related Articles:
- Java – How to get synchronized version of List ?
- Java – How to get synchronized version of Set ?
- Java – How to get synchronized version of Map ?
- Java – How to get synchronized version Collection ?
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
- https://docs.oracle.com/javase/7/docs/api/java/util/List.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
Happy Coding !!
Happy Learning !!