Java Thread Synchronization and Race Conditions
What is the likely issue when this program executes?
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 modifyData method is synchronized, guaranteeing that no race conditions occur during array modifications.
B
The printData method is unsynchronized, so it may read the array while it is being modified by the other threads.
C
The threads will never run concurrently due to synchronized methods, so the program is completely thread safe.
D
The data array is final, which means it is immune to concurrent modification issues.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE