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

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Java Thread Dump Analysis
  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • Understanding Lazy Evaluation in Java Streams
  • The Challenges and Pitfalls of Using Executors in Java

Trending

  • Behavior-Driven Development (BDD) Framework for Terraform
  • Advanced-Data Processing With AWS Glue
  • Navigating the Digital Frontier: A Journey Through Information Technology Progress
  • RRR Retro and IPL for Rewards and Recognition
  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
Like (47)
Save
Tweet
Share
32.7K 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

  • Java Thread Dump Analysis
  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • Understanding Lazy Evaluation in Java Streams
  • The Challenges and Pitfalls of Using Executors in Java

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: