Enhance server pack creation with CompletableFuture
Can the creation of a server pack be enhanced by implementing CompletableFuture? This may speed up configuration checks immensly, if done right.
See https://www.baeldung.com/java-completablefuture
Especially
- Running Multiple Futures in Parallel
When we need to execute multiple Futures in parallel, we usually want to wait for all of them to execute and then process their combined results.
The CompletableFuture.allOf static method allows to wait for completion of all of the Futures provided as a var-arg:
CompletableFuture future1
= CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future2
= CompletableFuture.supplyAsync(() -> "Beautiful"); CompletableFuture future3
= CompletableFuture.supplyAsync(() -> "World");CompletableFuture combinedFuture = CompletableFuture.allOf(future1, future2, future3);
combinedFuture.get();
assertTrue(future1.isDone()); assertTrue(future2.isDone()); assertTrue(future3.isDone());
Notice that the return type of the CompletableFuture.allOf() is a CompletableFuture. The limitation of this method is that it does not return the combined results of all Futures. Instead, we have to manually get results from Futures. Fortunately, CompletableFuture.join() method and Java 8 Streams API makes it simple:
String combined = Stream.of(future1, future2, future3) .map(CompletableFuture::join) .collect(Collectors.joining(" "));
assertEquals("Hello Beautiful World", combined);
The CompletableFuture.join() method is similar to the get method, but it throws an unchecked exception in case the Future does not complete normally. This makes it possible to use it as a method reference in the Stream.map() method.