Java 8: The Bad Parts
With Java 9 here, let's take a look at what its predecessor, Java 8, did well and, more importantly, where it left room for improvement.
Join the DZone community and get the full member experience.
Join For FreeJava 8 got many things right, and some things... not right. Apart from commonly recognized Java 8 caveats, there are a few which feel especially wrong.
1. Stream API vs. Custom Thread Pools
The Stream API made parallel processing of sequences/collections extremely easy — it became a matter of using one single keyword to do so.
However, there’s no easy way of controlling the parallelism level or providing a custom thread pool to run our tasks in – which might lead to thread pool exhaustion if we abuse the common pool.
There’s a commonly known workaround for that — by submitting a parallel Stream task to a custom pool:
ForkJoinPool customPool = new ForkJoinPool(42);
customPool
.submit(() -> list.parallelStream() /*...*/);
But there’s a problem with this approach:
“Note, however, that this technique of submitting a task to a fork-join pool to run the parallel stream in that pool is an implementation “trick” and is not guaranteed to work. Indeed, the threads or thread pool that is used for execution of parallel streams is unspecified. By default, the common fork-join pool is used, but in different environments, different thread pools might end up being used. (Consider a container within an application server.)”
Stuart Marks on StackOverflow
2. Lambda Expressions vs. Checked Exceptions
Leveraging declarative programming with lambda expressions eased working with various imperative Java idioms.
However, that’s not the case when lambda expressions meet checked exceptions.
Consider a simple Stream API pipeline:
list.stream()
.map(i -> i.toString())
.map(s -> s.toUpperCase())
.forEach(s -> System.out.println(s));
Now, let’s assume that all those operations throw checked exceptions:
list.stream()
.map(i - > {
try {
return i.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.map(s - > {
try {
return s.toUpperCase();
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.forEach(s - > {
try {
System.out.println(s);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
Not ideal.
What if we’re interested in checking if any of those operations (in the whole pipeline) throws an exception?
Then, we need to wrap the whole pipeline in a try-catch, which looks even more disturbing:
try {
list.stream()
.map(i - > {
try {
return i.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.map(s - > {
try {
return s.toUpperCase();
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.forEach(s - > {
try {
System.out.println(s);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
} catch (RuntimeException e) {
//...
}
There’s, of course, a clever hack for this but again:
“Just because you don’t like the rules, doesn’t mean its a good idea to take the law into your own hands. Your advice is irresponsible because it places the convenience of the code writer over the far more important considerations of transparency and maintainability of the program.”
Brian Goetz on StackOverflow
3. Stream API vs. Laziness
The Stream API is an implementation of the Lazy Sequence data structure – which key feature is laziness (duh!). This is why it’s possible to represent infinite sequences using them.
However, this isn’t always the case with the Stream API – for some reason, the flatMap() method evaluates eagerly:
Stream.of(42)
.flatMap(i -> Stream.generate(() -> 1))
.findAny();
Compare to similar idioms in Kotlin, Scala, or even Vavr that would be processed in O(1) instead of O(∞).
At the moment of writing this article, it’s been over three years since the bug’s been filed.
4. CompletableFuture.ofAll()
CompletableFuture is one of my favorite parts of Java 8 – finally, we can leverage an asynchronous model and not block on the Future.get().
While CompletableFuture got most of its API right, there’s one especially aching operation:
static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
It’s wrong mainly because of three things:
- It accepts multiple CompletableFutures holding an unspecified type <?>
- It accepts an array and not a collection
- It returns a CompletableFuture<Void>
Practically, the above characteristics make it suitable only for checking if all related futures completed.
That method could have been applicable to many more use-cases if it accepted a collection of futures of a known type and returned a future containing a collection of results instead of Void.
Published at DZone with permission of Grzegorz Piwowarek, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments