Bridge gaps and help overcome inconveniences with CompletableFuture
.
Status
Overview
- requires Java 8
- methods that collect the results of multiple completion stages into a
List
future, both with short-circuit semantics (fail early if an input completion stage fails) and without (guaranteed not to be completed while there are uncompleted input stages) - equivalent methods for
supplyAsync
,thenApply
,thenCompose
, etc. that accept functions throwing checked exceptions - method similar to Scala’s
Promise#completeWith
- method for unwrapping
CompletionException
- method for exception mapping
- methods for dealing with asynchronous “try-with-resources” scenarios
- tests have virtually full code coverage
License
Revised BSD (3-Clause) License
Binary Releases
Published releases (compiled for Java 8 and up) are available on Maven Central.
<dependency>
<groupId>net.florianschoppmann.java</groupId>
<artifactId>java-futures</artifactId>
<version>1.1.0</version>
</dependency>
Documentation
For current snapshot:
Release documentation is available by replacing “snapshot” in the URL by the respective version number (such as “1.1.0”).
Usage Examples
The following examples show some use cases of class Futures
provided by this project.
Collect the results of multiple completion stages into a List
future
CompletableFuture<Integer> sum(Set<CompletionStage<Integer>> set) {
return Futures.shortCircuitCollect(set)
.thenApply(list -> list.stream().mapToInt(Integer::intValue).sum());
}
Equivalent methods allowing for checked exceptions
CompletableFuture<Long> fileSize(CompletionStage<Path> filePathStage,
Executor executor) {
// Note that Files#size(Path) throws an IOException, hence it would have to
// be wrapped in the lambda expression passed to
// CompletionStage#thenApply(Function).
return Futures.thenApplyAsync(filePathStage, Files::size, executor);
}