Reputation: 15331
I have a relatively simple issue to solve, namely I would like to make all threads await a certain condition to happen and then proceed. It can be explained by the code below:
void doSth(){ //shared by multiple threads
...
if(!conditionMet())
await();
//procceed further
resetCondition()
}
I do not want to use locking and conditions, as it seems unnecessary. CountDownLatch
would be perfect, but I have to reset the latch, and CyclicBarrier
would not work either because I have no idea how many threads need to call await. Also, when the signal is sent to awaiting threads, they should all be released and proceed. How would you guys approach this?
Upvotes: 2
Views: 580
Reputation: 62439
I don't really see why you wouldn't want to use locks? Any "barrier" mechanism will internally use some form of synchronization, so there's no real "unleash all threads at the same time" solution.
Best I can come up with:
private final Object lock = new Object();
void doSth() { //shared by multiple threads
...
synchronized(lock) {
while(!conditionMet()) {
lock.wait();
}
}
}
void release() {
synchronized(lock) {
resetCondition();
lock.notifyAll();
}
}
Upvotes: 0
Reputation: 40256
I recommend Phaser
I have no idea how many threads need to call await.
For each thread that eventually needs to wait, invoke phaser.register()
[register doesn't wait, it tells the phaser to expect another thread to either wait or to trip the barrier]
CountDownLatch would be perfect, but I have to reset the latch
Once a thread completes, invoke phaser.arriveAndAwaitAdvance()
. At that point, all threads will wait there until the number of threads registered == number of threads arrived
.
Upvotes: 2
Reputation: 116828
I do not want to use locking and conditions, as it seems unnecessary.
Why? This smacks of premature optimization to me. If you don't know how many threads there are then you can't use CountDownLatch
. This seems to me to be a perfect use case of standard locks and conditions. The only time we worry about their use is when we are trying hard not to get threads to block. But in this case blocking is exactly what you want.
Upvotes: 1