Are you taking CLEP classes? Try clep.ai
| 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

Mark
< Prev
Next >

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.

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.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|