简体   繁体   中英

Java concurrency - reset condition after leaving method

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 Lock s with Condition s, 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM