Question

I'm writing a program that has to modify a List in two ways. Although this implementation works perfectly, it fails to let the second thread acquire the lock:

Node head = new Node(new Object(), null);
public static ReentrantLock lock = new ReentrantLock();
...

boolean add(Object o){
    lock.lock();
    Node current = head;
    Node previous = head.next;

    if(head.next==null){
        head.addNext(new Node(o,null));
        return true;
    }
    while(!(current.next == null)){
        current=current.next;
        previous=previous.next;
    }
    current.addNext(new Node(o,null));
    lock.unlock();
    return true;    
}

Maybe someone knows why is that?

Was it helpful?

Solution

There are branches of code that will never allow the unlock to be invoked. For instance in add

if(head.next==null){
    head.addNext(new Node(o,null));
    return true;
}

You return without unlocking. You should follow the lock try finally unlock semantics.

lock.lock();
try{
   ... do stuff 
   return true;
}finally{
   lock.unlock();
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top