From 0e4858a1846ba2525f5c9c600a0c7b6320ec8385 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Dyda?= Date: Thu, 17 Nov 2022 14:50:38 +0100 Subject: [PATCH] Java 11 does not have AutoClosable on ForkJoinPool (that's a pity). --- .../pl/amu/edu/demo/stream/StreamExample.java | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/demo/03/src/main/java/pl/amu/edu/demo/stream/StreamExample.java b/demo/03/src/main/java/pl/amu/edu/demo/stream/StreamExample.java index 247c55d..cc32bf6 100644 --- a/demo/03/src/main/java/pl/amu/edu/demo/stream/StreamExample.java +++ b/demo/03/src/main/java/pl/amu/edu/demo/stream/StreamExample.java @@ -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 getPeople() {