CopyOnWriteArrayList Thread Safety
Why is CopyOnWriteArrayList used in this example, and what is its primary advantage?
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 locks the entire list during iteration, ensuring that no modifications occur concurrently.
B
It improves performance by completely eliminating synchronization overhead in all operations.
C
It synchronizes only the addElements() method while leaving iterateElements() unsynchronized for speed.
D
It provides thread-safe iteration by maintaining a snapshot of the list, thereby preventing ConcurrentModificationExceptions.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE