The problem and the solution using Future

To demonstrate and appreciate the power of CompletableFuture, let's start with a problem implemented using just Future and then see how much more effectively it can be solved with CompletableFuture. Let's imagine that we are tasked with modeling a building that consists of four stages:

  • Collecting materials for the foundation, walls, and roof
  • Installing the foundation
  • Raising up the walls
  • Constructing and finishing the roof

In the traditional sequential programming for the single thread, the model would look like this:

StopWatch stopWatch = new StopWatch();Stage failedStage;String SUCCESS = "Success";stopWatch.start();String result11 = doStage(Stage.FoundationMaterials);String result12 = doStage ...

Get Java 9 High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.