Java 11 does not have AutoClosable on ForkJoinPool (that's a pity).
This commit is contained in:
parent
ad3998bb61
commit
0e4858a184
@ -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() {
|
||||
|
Loading…
Reference in New Issue
Block a user