I'm trying to stimulate the scenario of deadlocks in the shared array using Reentrant Locks.
class SharedArray {
private int ff[];
private Lock keys[];
public SharedArray(int n){
ff = new int[n];
keys = new ReentrantLock[n];
for(int j = 0; j < n; j++){
ff[j] = (int)(Math.random()*100);
keys[j] = new ReentrantLock();
}
}
void swap(int j, int k) {
keys[j].lock(); keys[k].lock();
int t = ff[j]; ff[j] = ff[k]; ff[k] = t;
keys[j].unlock(); keys[k].unlock();
}
}
Here the swap method is deadlock prone which I have achieved. for example if Thread 1 is swap(7,4) and at the same time Thread 2 is swap(4,7) this will raised the deadlock.
How do I prevent it from deadlock. What sort of refactoring is required. I have tried to used synchronized but I'm looking for possibly a reliable way to solve that.
synchronized void swap(int j, int k) {
keys[j].lock(); keys[k].lock();
int t = ff[j]; ff[j] = ff[k]; ff[k] = t;
keys[j].unlock(); keys[k].unlock();
}