1.

How can you synchronize an ArrayList in Java?

Answer»

An ArrayList can be synchronized using the following two ways :

  • Using Collections.synchronizedList() method:
    All access to the BACKUP list must be done through the returning list in order to perform serial access. When iterating over the returned list, it is critical that the user manually synchronizes.
    Example:
import java.util.*; class InterviewBit{ public static void main (String[] ARGS) { List&LT;String> synchronized_list = Collections.synchronizedList(new ArrayList<String>()); synchronized_list.ADD("learn"); synchronized_list.add("practice"); synchronized_list.add("solve"); synchronized_list.add("interview"); synchronized(synchronized_list)// must be declared { Iterator it = synchronized_list.iterator(); while (it.hasNext()) System.out.println(it.next()); } }}

Output:

learnpracticesolveinterview
  • Using CopyOnWriteArrayList:

Syntax:

CopyOnWriteArrayList<T> list_name = new CopyOnWriteArrayList<T>();

Here, a thread-safe variant of ArrayList is created. T represents generic.

All mutative actions (e.g. add, set, remove, etc.) are implemented by generating a separate copy of the underlying array in this thread-safe variation of ArrayList. It accomplishes thread safety by generating a second copy of List, which differs from how vectors and other collections achieve thread-safety.

Even if copyOnWriteArrayList is modified after an iterator is formed, the iterator does not raise CONCURRENTMODIFICATIONEXCEPTION because the iterator is iterating over a separate copy of ArrayList while a write operation is occurring on another copy of ArrayList.

Example:

import java.io.*;import java.util.Iterator;import java.util.concurrent.CopyOnWriteArrayList; class InterviewBit{ public static void main (String[] args) { CopyOnWriteArrayList<String> synchronized_list = new CopyOnWriteArrayList<String>();// creating a thread-safe Arraylist. // Adding strings to the synchronized ArrayList synchronized_list.add("learn"); synchronized_list.add("practice"); synchronized_list.add("solve"); synchronized_list.add("interview"); System.out.println("The synchronized ArrayList has the following elements :"); // Iterating on the synchronized ArrayList using an iterator. Iterator<String> it = synchronized_list.iterator(); while (it.hasNext()) System.out.println(it.next()); }}

Output:

The synchronized ArrayList has the following elements :learnpracticesolveinterview


Discussion

No Comment Found