Java Thread Synchronization and Race Conditions
Consider the following SharedResource class. What is a potential issue that may arise during the execution of the main method?
public class SharedResource {
private final int[] data = new int[10];
public synchronized void modifyData() {
for (int i = 0; i < data.length; i++) {
data[i] = data[i] + 1;
}
}
public void printData() {
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + " ");
}
}
public static void main(String[] args) {
SharedResource sr = new SharedResource();
Thread t1 = new Thread(() -> sr.modifyData());
Thread t2 = new Thread(() -> sr.modifyData());
t1.start();
t2.start();
sr.printData();
}
}
A
The data array is final, which means it is immune to concurrent modification issues.
B
The threads will never run concurrently due to synchronized methods, so the program is completely thread safe.
C
The modifyData method is synchronized, guaranteeing that no race conditions occur during array modifications.
D
The printData method is unsynchronized, so it may read the array while it is being modified by the other threads.
Question Leaderboard
Not enough data yet to show leaderboard.
