Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java equivalent of Golang's WaitGroup

Tags:

java

go

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.

like image 320
Adam Gent Avatar asked Apr 15 '15 16:04

Adam Gent


3 Answers

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();
        }
    }

}
like image 66
user82928 Avatar answered Nov 13 '22 01:11

user82928


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
like image 43
kostya Avatar answered Nov 13 '22 00:11

kostya


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();
    }
}

like image 1
Yao Yuan Avatar answered Nov 13 '22 00:11

Yao Yuan