DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Alternative Structured Concurrency
  • Beyond Java Streams: Exploring Alternative Functional Programming Approaches in Java
  • Using Java Stream Gatherers To Improve Stateful Operations
  • Java Virtual Threads and Scaling

Trending

  • Introducing senro: A Pipeline Engine You Program in Go
  • Avoiding AI Debt as a Team
  • 9 Practical Ways to Fix Laravel Performance Issues in Production
  • When Production Stops Moving: Running Claude Code Across a Distributed Enterprise Integration Team

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Java 8: The Bad Parts

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.

By 
Grzegorz Piwowarek
·
Dec. 14, 17 · Opinion
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
34.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Java 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.

Java (programming language) Stream (computing) Thread pool

Published at DZone with permission of Grzegorz Piwowarek. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Alternative Structured Concurrency
  • Beyond Java Streams: Exploring Alternative Functional Programming Approaches in Java
  • Using Java Stream Gatherers To Improve Stateful Operations
  • Java Virtual Threads and Scaling

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook