Lambdas, Executors, and Callables, Oh My!

This post complements my previous one on benchmarking.
All code from this post is available on GitHub: https://github.com/JonasJSchreiber/Primitive-Benchmarking

Lambda Syntax

There are quite a few ways to iterate in Java. Let’s take a look at the traditional “for” loop, written three different ways, each doing the same thing: multiplying two matrices.
Using a declared iterator, with terminating conditions:
good
Using Collections and a “foreach” loop:
better
Using lambda syntax:
best
The lambda syntax is broken into separate lines because I like tidy code. It’s really one statement, doing nested loops.

Executors

Like your traditional Thread implementing the Runnable interface, Executors do the same, but provide quite a few additional benefits. The most notable of these benefits is a JVM-managed thread pool.
executors

Futures and Callables

Callables are like runnables but instead of implementing a void work that goes off and does its work, a callable will return the results to the instantiating method. This is great, but it provides no benefit if you are just waiting for the results before invoking other threads. Enter Futures.
futures
Much more “ceremony” than with Executors, but it’s still powerful and a good tool to have in your belt.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *