Java Thread Synchronization and Visibility
In the provided code, a writer thread modifies a shared ArrayList while a reader thread accesses it. Which approach best ensures that the reader thread will observe the most recent list size?
import java.util.ArrayList;
public class VisibilityTest {
static ArrayList<Integer> list = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
Thread writer = new Thread(() -> {
for (int i = 0; i < 10; i++) {
list.add(i);
try { Thread.sleep(20); } catch (InterruptedException e) {}
}
});
Thread reader = new Thread(() -> {
try { Thread.sleep(50); } catch (InterruptedException e) {}
System.out.println(list.size());
});
writer.start();
reader.start();
writer.join();
reader.join();
}
}
A
Encapsulate both the write and read operations within a synchronized block on the shared list
B
Replace ArrayList with LinkedList
C
Insert Thread.sleep calls between operations to ensure memory consistency
D
Declare the ArrayList as volatile
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE