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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

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

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

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

Related

  • Javac and Java Katas, Part 2: Module Path
  • Javac and Java Katas, Part 1: Class Path
  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]

Trending

  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • Using Python Libraries in Java
  • Infrastructure as Code (IaC) Beyond the Basics
  1. DZone
  2. Coding
  3. Java
  4. Lambdas and Side Effects

Lambdas and Side Effects

By 
Peter Lawrey user avatar
Peter Lawrey
·
Sep. 16, 14 · Interview
Likes (1)
Comment
Save
Tweet
Share
7.7K Views

Join the DZone community and get the full member experience.

Join For Free

Overview

Java 8 has added features such as lambdas and type inference. This makes the language less verbose and cleaner, however it comes with more side effects as you don't have to be as explicit in what you are doing.

The return type of a lambda matters

Java 8 infers the type of a closure.  One way it does this is to look at the return type (or whether anything is returned)  This can have a surprising side effect.  Consider this code.
ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(() -> {
    try(Scanner scanner = new Scanner(new FileReader("file.txt"))) {
        String line = scanner.nextLine();
        process(line);
    }
    return null;
});
This code compiles fine. However, the line return null; appears redundant and you might be tempted to remove it.  However if you remove the line, you get an error.
Error:(12, 39) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
This is complaining about the use of FileReader. What has the return null got to do with catching an uncaught exception !?

Type inference.

ExecutorService.submit() is an overloaded method.  It has two methods which take one argument.
ExecutorService.submit(Runnable runnable);
ExecutorService.submit(Callable callable);
Both these methods take no arguments, so how does the javac compiler infer the type of the lambda? It looks at the return type.  If you return null; it is aCallable<Void> however if nothing is returned, not even null, it is a Runnable. 
Callable and Runnable have another important difference. Callable throws checked exceptions, however Runnable doesn't allow checked exceptions to be thrown.
The side effect of returning null is that you don't have to handle checked exceptions, these will be stored in the Future<Void> submit() returns.  If you don't return anything, you have to handle checked exceptions.

Conclusion

While lambdas and type inference remove significant amounts of boiler plate code, you can find more edge cases, where the hidden details of what the compiler infers can be slightly confusing.

Footnote

You can be explicit about type inference with a cast. Consider this
Callable<Integer> calls = (Callable<Integer> & Serializable) () -> { return null; }
if (calls instanceof Serializable) // is true
This cast has a number of side effects. Not only does the call() method return anInteger and a marker interface added,  the code generated for the lambda changes i.e. it adds a writeObject() and readObject() method to support serialization of the lambda.
Note: Each call site creates a new class meaning the details of this cast is visible at runtime via reflection.
Side effect (computer science) Call site Java (programming language) Serialization Javac Interface (computing)

Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Javac and Java Katas, Part 2: Module Path
  • Javac and Java Katas, Part 1: Class Path
  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]

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!