| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice TestPractice Test
About Exam
hard Solved by 1 students
Synchronizing Compound ArrayList Operations
< Prev
Next >

Consider the provided code snippet. Why is it necessary to enclose the sequence of get, remove, and add operations within a single synchronized block?

import java.util.ArrayList;

public class CompoundOperation {
    static ArrayList<Integer> list = new ArrayList<>();
    public static void main(String[] args) {
        // Pre-populate the list
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        Thread t1 = new Thread(() -> {
            synchronized(list) {
                int val = list.get(0);
                list.remove(0);
                list.add(val + 100);
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized(list) {
                int val = list.get(1);
                list.remove(1);
                list.add(val + 200);
            }
        });
        t1.start();
        t2.start();
    }
}
A

To prevent the ArrayList from growing during the operation

B

To improve performance by reducing the number of separate lock acquisitions

C

Because synchronizing only read operations is sufficient for thread safety

D

To ensure that the sequence of read, remove, and add operations occurs atomically without interference

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