Java — Threading Basics — Futures & Callables

Overview

A Future is an object in Java which represents the response from a Callable object after its been executed.

Example

You have a piece of logic which fetches and returns a String once complete. This takes 10 seconds to execute.
You want to execute 10 of these same tasks in parallel, so you create a threadpool with a fixed size of 10.

You create 10 Callable objects which contain your logic to fetch the String. You submit these callables to the threadpool for execution, and you receive a Future object for each callable you submit. This Future object represents the String response.

However, your code takes 10 seconds to execute. But you receive the Future object immediately after you submit the task.

So the value of the Future initially is not populated. At this point, it represents an object which will in the future contain the response you expect. It is an object which you can use to get that response once the task has been complete.

Why is this useful?

The main reason is that it is a simple interface allowing you to get the response from a piece of parallel code.
However another big benefit is: you can perform other pieces of logic while you wait for the response. You have the option if you want to either await the operation to complete, or you could execute another 100 lines of code first, then check if its complete and get the response.

How to do this?

You can do this by calling the get() method which will pause execution and wait for the response of the Future task. Otherwise, you can perform other operations and continuously poll the Future checking the isDone() method.

See an example held in my Github repository here

--

--