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