Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice TestPractice Test
About Exam
hard

Synchronizing Compound ArrayList Operations

Mark
< 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

Because synchronizing only read operations is sufficient for thread safety

B

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

C

To improve performance by reducing the number of separate lock acquisitions

D

To prevent the ArrayList from growing during the operation

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|