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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Using Java Stream Gatherers To Improve Stateful Operations
  • Java Virtual Threads and Scaling
  • Thread-Safety Pitfalls in XML Processing
  • Java Stream API: 3 Things Every Developer Should Know About

Trending

  • How to Convert XLS to XLSX in Java
  • Data Quality: A Novel Perspective for 2025
  • Advancing Your Software Engineering Career in 2025
  • Navigating and Modernizing Legacy Codebases: A Developer's Guide to AI-Assisted Code Understanding
  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 user avatar
Grzegorz Piwowarek
·
Dec. 14, 17 · Opinion
Likes (47)
Comment
Save
Tweet
Share
33.8K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Using Java Stream Gatherers To Improve Stateful Operations
  • Java Virtual Threads and Scaling
  • Thread-Safety Pitfalls in XML Processing
  • Java Stream API: 3 Things Every Developer Should Know About

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!