Golang has something called a WaitGroup
which is sort of like in Java a CompletionService
or a CountDownLatch
or a Semaphore
or some combination of the latter.
I'm not entirely sure how you would implement a WaitGroup in Java. I would imagine a custom CompletionService with some sort of Poison message would be the route to go (since queues can't say when they are done) but perhaps there is a better concurrent data structure/lock?
EDIT I posted a possible solution below using Semaphore
that I think is more analogous than using thread.join
.
public class WaitGroup {
private int jobs = 0;
public synchronized void add(int i) {
jobs += i;
}
public synchronized void done() {
if (--jobs == 0) {
notifyAll();
}
}
public synchronized void await() throws InterruptedException {
while (jobs > 0) {
wait();
}
}
}
WaitGroup
has Add(delta)
method that can be called after a WaitGroup
has been created. CountDownLatch
doesn't support this, number of tasks needs to be specified in advance. JDK7 Phaser
can be used instead in this case:
phaser.register = wg.Add(1)
phaser.arrive = wg.Done
phaser.await = wg.Wait
Thanks to @kostya's answer. I write a WaitGroup class with Phaser
public class WaitGroup {
Phaser phaser = new Phaser(1);
public void add() {
phaser.register();
}
public void done() {
phaser.arrive();
}
public void await() {
phaser.arriveAndAwaitAdvance();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With