Thread-Safe ArrayList Compound Operations
What is required to safely execute a compound operation, such as checking if an ArrayList is empty before accessing an element, when the list is shared among multiple threads?
import java.util.ArrayList;
public class CompoundAction {
static ArrayList<Integer> list = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
synchronized(list) {
if (!list.isEmpty()) {
list.remove(0);
}
}
});
Thread t2 = new Thread(() -> {
synchronized(list) {
if (!list.isEmpty()) {
System.out.println(list.get(0));
}
}
});
t1.start();
t2.start();
}
}
A
Rely on the thread-safety of ArrayList which is inherent by default
B
Declare the ArrayList as volatile
C
Enclose the entire compound operation in a synchronized block on the shared object
D
Synchronize each individual method call separately
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | kaisuki | 2 | 2 | 0m 00s | 200 |
| #2 | ponneban000 | 0 | 1 | 1m 14s | -84 |
| #3 | y.seong2027 | 0 | 1 | 2m 39s | -169 |
APFIVE