Correct use of locking / unlocking for Java reentrant locks

I have a homework assignment called "H2O Problem" where I have to implement a class called H2OBarrier that has 3 methods.

  • HReady, a method called when a hydrogen atom (stream) is ready
  • OReady, a method called when an oxygen atom (flow) is ready
  • makeWater, a method called when 2 hydrogen atoms and one oxygen atom are ready

I have to do it with Java Reentrant locks and conditions.

This is my code so far and I am wondering if I am using locking and unlocking correctly.

public class H2OBarrier {

int hCount;
int oCount;

Lock lock = new ReentrantLock();
Condition hWait = lock.newCondition();
Condition oWait = lock.newCondition();

public void HReady() {
    lock.lock();
    hCount++;

    try {
        hWait.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

public void OReady(){
    lock.lock();
    oCount++;

    try {
        while(hCount<2 && oCount<1){
            oWait.await();
        }   
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        makeWater();
    }


}

public void makeWater(){
    hCount--;
    hWait.signal();
    lock.unlock();

    hCount--;
    hWait.signal();
    lock.unlock();

    oCount--;
    oWait.signal();
    lock.unlock();

}

} 

      

Should I call unlock () somewhere other than my makeWater method? The entire flow of the program seems to make pretty logical sense to me, I just wanted to make sure everything looks right.

+3


source to share


1 answer


Your code creates a dead end. Imagine 5 o atoms go through first, 5 go to o queue created by await (). Now it doesn't matter if 2h atoms pass, all h atoms will wait automatically due to your code.



+2


source







All Articles