CopyOnWriteArrayList Thread Safety
Consider the following code. What is the primary advantage of using a CopyOnWriteArrayList in this multithreaded context?
import java.util.concurrent.CopyOnWriteArrayList;
public class SafeIteration {
private CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
public void addElements() {
for(int i = 0; i < 50; i++){
list.add(i);
}
}
public void iterateElements() {
for(Integer num: list) {
System.out.println(num);
try { Thread.sleep(10); } catch (InterruptedException e) {}
}
}
public static void main(String[] args) throws InterruptedException {
SafeIteration si = new SafeIteration();
Thread t1 = new Thread(() -> si.addElements());
Thread t2 = new Thread(() -> si.iterateElements());
t1.start();
t2.start();
t1.join();
t2.join();
}
}
A
It synchronizes only the addElements() method while leaving iterateElements() unsynchronized for speed.
B
It locks the entire list during iteration, ensuring that no modifications occur concurrently.
C
It provides thread-safe iteration by maintaining a snapshot of the list, thereby preventing ConcurrentModificationExceptions.
D
It improves performance by completely eliminating synchronization overhead in all operations.
Question Leaderboard
Not enough data yet to show leaderboard.
