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.
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!!
import java.util.concurrent.locks.ReentrantLock;
class Main {
public static void main(String[] args) throws InterruptedException {
// Generate List
Node first = new Node();
Node current = first;
for(int i = 0; i < 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();
}
}
class FirstThread extends Thread {
Node current;
FirstThread(Node start) {
this.current = start;
}
public void run() {
// =================> HAND OVER HAND LOCKING <=================
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();
}
}
class SecondThread extends Thread {
Node current;
SecondThread(Node start) {
current = start;
}
public void run() {
while(current != null) {
current.value++;
current = current.next;
}
}
}
class Node {
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();
}
}
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.