Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a short-hand to call several functions in parallel in Java?

Given I have a function in Java which has to do a lot of work. This work consists of several different things to do, which are defined in their own functions and are independent of each other.

void myFunction() {
    foo();
    bar();
}

However, these functions run one after the other (just as I coded it), which is not necessary here and makes the whole function run longer than necessary. Running both functions in its own thread requires significantly more code:

void myFunction() {
    UncaughtExceptionHandler eh = (th, t) -> { throw new UndeclaredThrowableException(t); };
    try {
        Thread foo = new Thread(() -> foo());
        Thread bar = new Thread(() -> bar());
        foo.setUncaughtExceptionHandler(eh);
        bar.setUncaughtExceptionHandler(eh);
        foo.start();
        bar.start();
        foo.join();
        bar.join();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

So I wonder if there is some built-in approach in newer Java versions to do this more efficiently, something like:

Threads.doParallel(
    () -> foo(),
    () -> bar()
);
like image 804
Matthias Ronge Avatar asked Oct 19 '25 14:10

Matthias Ronge


1 Answers

The shortest I get, using CompletableFutures is this :

CompletableFuture.allOf(
        CompletableFuture.runAsync(new FutureTask<Void>(() -> foo(), null)),
        CompletableFuture.runAsync(new FutureTask<Void>(() -> bar(), null))
).get();

This doesn't have the handling for excptions in foo() or bar(). But we can add that, sacrificing some brevity :

CompletableFuture.allOf(
        CompletableFuture.runAsync(new FutureTask<Void>(() -> foo(), null)),
        CompletableFuture.runAsync(new FutureTask<Void>(() -> bar(), null))
)
.exceptionally(t -> {
    throw new UndeclaredThrowableException(t);
})
.get();
like image 139
bowmore Avatar answered Oct 21 '25 03:10

bowmore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!