Java concurrency - reset condition after leaving method

478 views Asked by At

I am trying to figure out a solution to the following problem:

public void signal(){
   //resets condition and signals threads blocked below
}

public void getValue(){

    waitOnCondition(); //block if a condition is not met. When signalled, all threads should proceed and get the value

    //get value

    resetCondition(); //reset condition, so that the next thread that executes this method blocks on the method above

}

The issue I am facing seems to be simple, but I am struggling to see how all the edge cases can be captured.

One solution might be to use Locks with Conditions, then all threads witing on waitOnCondition are going to await until a flag is set to true and then proceed, for example. The thread executing signal() would then use the same lock, set the flag to true and signal. Then, the released threads would reacquire the lock to set the condition to false. This, however, does not guarantee that all the threads are going to reach the getValue point. For instance:

Thread 1 and 2 are waiting, get the signal. After being signalled, thread 1 reacquires the lock, checks the condition, now true, and proceeds. gets the value, acquires the lock and sets condition to false. Thread 2, now sees the condition still as false, and blocks again.

Another solution, quite neat and elegant, would be to use a CountDownLatch. This guarantees that all the threads are going to proceed. This is, however, not resettable. Any other ideas or comments?

1

There are 1 answers

0
Andrey Chaschev On

Seems like CyclicBarrier is what you need. It is resettable and also allows to trigger a barrier action when all parties are there.

There is also Phaser which is an advanced version of CyclicBarrier and it requires JDK 7 to run.