title: locking each item in array by java
body: <p>suppose we have these classes:</p>
  
  <pre><code>public  class Record {
      int key;
      int value;
      Record(){
          this.key=0;
          this.value=0;
      }
      Record(int key,int value){
          this.key=key;
          this.value=value;
      }
      public  class Table {
          static final Record[] table = new Record [100];
          static final Object[] locks = new Object[table.length];
          static{
          for(int i = 0; i &lt; table.length; i++) {
              locks[i] = new Object();
          }
  
  
          table[0]=new Record(0,0);
          table[1]=new Record(1,10); 
          table[2]=new Record(2,20);
          table[3]=new Record(3,30);
      }
  }
  </code></pre>
  
  <p>And i want to implement in TRansaction class these method</p>
  
  <pre><code>void setValueByID(int key, int value)
  </code></pre>
  
  <p>The key-value pair (record) is locked(it cannot be read/written from other transactions) until the setValueByID method finishes.</p>
  
  <pre><code>int getValueByID(int key)
  </code></pre>
  
  <p>The key-value pair (record) is locked  until the transaction <strong>commits</strong></p>
  
  <pre><code>void commit()
  </code></pre>
  
  <p>it unlocks all the key-value pairs (records) locked in the current transaction</p>
  
  <p><strong>So, my implementation is :</strong></p>
  
  <pre><code>class Transaction extends Thread {
  //there is no problem here  
      public void setValueByID(int key, int value){
  
      synchronized(Table.locks[key]) {
       Table.table[key].key=key;
  
      }   
      }
      //the problem is here...
      //how can i make other thread wait until current thread calls Commit()
      public int getValueByID(int key){
              int value=0; 
              synchronized(Table.locks[key]){
              value= Table.table[key].key;
       }
       return value;
  } 
  
  
  void commit(){
  }
  </code></pre>
  
  <p>Ahmad</p>