| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Iteration
Start Practice TestPractice Test
About Exam
hard
CopyOnWriteArrayList Thread Safety
< Prev
Next >

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.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy