Synchronizing Compound ArrayList Operations
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
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE