title: Java locks: Hand over hand locking through list
body: <p>I'm trying to understand the java.util.concurrent.locks library and wanted to implement two threads which run through a list, whereas the second thread should not overtake (take the lead) the first thread. Specifically, I wanted to implement hand-over-hand locking.</p>
  
  <p>I wrote the following code, wich doesn't work. After the two threads ran through the list, the nodes take the value 41 after a certain point. This means the second thread edited them before the first one did. I googled a lot and also had a look at similar question but still couldn't figure it out. I really appreciate your help, thanks!!</p>
  
  <pre><code>import java.util.concurrent.locks.ReentrantLock;
  </code></pre>
  
  <p>class Main {</p>
  
  <pre><code>public static void main(String[] args) throws InterruptedException {
      // Generate List
      Node first = new Node();
      Node current = first;
      for(int i = 0; i &lt; 50; i++) {
          current.next = new Node();
          current = current.next;
      }
  
      // run Threads
      FirstThread a = new FirstThread(first);
      SecondThread b = new SecondThread(first);
      a.start();
      b.start();
      a.join();
      b.join();
  
      // Print result
      first.print();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>class FirstThread extends Thread {</p>
  
  <pre><code>Node current;
  
  FirstThread(Node start) {
      this.current = start;
  }
  
  public void run() {
      // =================&gt; HAND OVER HAND LOCKING &lt;=================
      current.lock.lock();
      while(current.next != null) {
          current.value = 41;
          current.next.lock.lock();
          current.lock.unlock();
          current = current.next;
      }
      current.value = 41;
      current.lock.unlock();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>class SecondThread extends Thread {</p>
  
  <pre><code>Node current;
  
  SecondThread(Node start) {
      current = start;
  }
  
  public void run() {
      while(current != null) {
          current.value++;
          current = current.next;
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>class Node {</p>
  
  <pre><code>ReentrantLock lock;
  Node next;
  int value;
  
  Node() {
      lock = new ReentrantLock();
      next = null;
      value = 0;
  }
  
  public void print() {
      Node current = this;
      while(current != null) {
          System.out.print(current.value + " ");
          current = current.next;
      }
      System.out.println();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>PS: I know I should actually insert try and finally blocks if the thread gets interrupted but didn't know where so just neglected that event.</p>