Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to synchronize ArrayList in Java with Example

Synchronization we have discussed in detail on java multithreading interview questions and answers.
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
ListString> synchronizedarraylist =
Collections.synchronizedList(new ArrayListString>());

//Adding elements to synchronized ArrayList
synchronizedarraylist.add("Basketball");
synchronizedarraylist.add("Baseball");
synchronizedarraylist.add("Football");

System.out.println("Synchronized ArrayList Iteration:");
synchronized(synchronizedarraylist) {
IteratorString> 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
CopyOnWriteArrayListString> al = new CopyOnWriteArrayListString>();

//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
IteratorString> iterator = al.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
}

Output


Showing synchronized ArrayList Elements:
Basketball
Baseball
Football


This post first appeared on Java Hungry, please read the originial post: here

Share the post

How to synchronize ArrayList in Java with Example

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×