Java Concurrency and Deadlock
What concurrency problem is most likely with the MultiLock class?
public class MultiLock {
private int[] arrayA = new int[2];
private int[] arrayB = new int[2];
public void methodOne() {
synchronized(arrayA) {
try { Thread.sleep(50); } catch (InterruptedException e) {}
synchronized(arrayB) {
arrayA[0] = 10;
}
}
}
public void methodTwo() {
synchronized(arrayB) {
try { Thread.sleep(50); } catch (InterruptedException e) {}
synchronized(arrayA) {
arrayB[0] = 20;
}
}
}
public static void main(String[] args) {
MultiLock ml = new MultiLock();
Thread t1 = new Thread(() -> ml.methodOne());
Thread t2 = new Thread(() -> ml.methodTwo());
t1.start();
t2.start();
}
}
A
Arrays are inherently thread-safe, so synchronizing on them is unnecessary and does not introduce any problems.
B
The sleep calls ensure that thread execution is serialized, thereby preventing any concurrency issues.
C
Deadlock is impossible because the locked objects are mutable arrays, which cannot cause deadlock conditions.
D
The lock ordering in methodOne and methodTwo is reversed, which can lead to a deadlock if both methods are executed concurrently.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE