InterviewSolution
| 1. |
How can you synchronize an ArrayList in Java? |
|
Answer» An ArrayList can be synchronized using the following two ways :
Output: learnpracticesolveinterview
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 |
|