“Hello world” example of Futures in Java 8

Daniel Blazevski
2 min readOct 15, 2017

--

If you maybe-kinda-sorta have a idea of what a Future is in Java, and want a concise post with a functional “Hello world” example of code to build off of and a diagram worth 1000 words, then this post is for you!

Functional examples are a great way to complement API docs and speed up how one learns a new framework/API/etc and can be used to iterate on for your particular use case. This post will not describe the Futures API since that exists elsewhere.

Hello world using Futures in Java 8

The “Hello World” example will take two strings, simultaneously reverses both of them, and concatenates the two strings once both of them have been reversed. See the diagram below for a illustration.

You might be thinking “well jeez, reversing a string is a very quick task that does not need to be done asynchronously”, and you would be correct! To make the example more interesting, I added a “slow reverse” method that waits 500ms and then reverses the string.

The code below will run in about 600ms, even though there are two separate calls to wait 500ms, showing the benefit of doing the tasks asynchronously. Code can also be found on Github here.

--

--

Daniel Blazevski

Software Engineer at Spotify. Distributed systems and data