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