Java 11 does not have AutoClosable on ForkJoinPool (that's a pity).

This commit is contained in:
Paweł Dyda 2022-11-17 14:50:38 +01:00
parent ad3998bb61
commit 0e4858a184

View File

@ -21,19 +21,18 @@ public class StreamExample {
// Huge number of threads!
getPeople().parallel().mapToInt(Person::getAge).average().ifPresent(System.out::println);
// Better solution, limiting the number of threads
try (var pool = new ForkJoinPool(8)) {
var maybeAverageAgeFuture = pool.submit(
() -> getPeople().parallel().mapToInt(Person::getAge).average()
);
// io.vavr.control.Try
var triedAverageAge = Try.of(
() -> maybeAverageAgeFuture.get(30, TimeUnit.SECONDS)
).map(OptionalDouble::orElseThrow);
if (triedAverageAge.isSuccess()) { // there is also isFailure()
System.out.println(triedAverageAge.get()); // instead of if, one can use getOrElse()
}
// IDEA complains about try-with-resources, but that does not work with Java 11 (try higher)
@SuppressWarnings("resource") var pool = new ForkJoinPool(8);
var maybeAverageAgeFuture = pool.submit(
() -> getPeople().parallel().mapToInt(Person::getAge).average()
);
// io.vavr.control.Try
var triedAverageAge = Try.of(
() -> maybeAverageAgeFuture.get(30, TimeUnit.SECONDS)
).map(OptionalDouble::orElseThrow);
if (triedAverageAge.isSuccess()) { // there is also isFailure()
System.out.println(triedAverageAge.get()); // instead of if, one can use getOrElse()
}
}
private Stream<Person> getPeople() {