title: SharedArray Deadlock and raise Conditions
body: <p>I'm trying to stimulate the scenario of deadlocks in the shared array using Reentrant Locks.</p>
  
  <pre><code>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 &lt; 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(); 
      }       
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <pre><code>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(); 
  } 
  </code></pre>