Tuhin Subhra Mandal
Tuhin Subhra Mandal

Reputation: 523

CompletableFuture chaining

I am looking for suggestion about chaining multiple methods which are CompletableFutures.

Let's say I need to do 3 operations.

  1. search form master table
  2. if data not present in master table insert into master
  3. Master tables primary key will be used to insert some data to child table.

Hypothetically my methods are something like this:

public static CompletableFuture<Long> searchMaster() {
    return CompletableFuture.supplyAsync (() -> 100L);
}

public static CompletableFuture<Long> insertIntoMaster() {
    return CompletableFuture.supplyAsync (() -> 200L);
}

public static CompletableFuture<Long> insertIntoChildDB() {
    return CompletableFuture.supplyAsync (() -> 300L);
}

Now my requirement is:

first method returns an id. I will pass that id to the second method. On successful result from second method, which will return a CompletableFuture, this primaryid will be passed on to the third method, which will insert some data in the child table.

How do I do the chaining with JDK8 CompletableFutures.

Upvotes: 3

Views: 2055

Answers (1)

John Kugelman
John Kugelman

Reputation: 361555

Use one of the thenCompose() methods, which flatten futures much like Stream.flatMap() flattens streams:

CompletableFuture<Long> future = searchMaster()
    .thenCompose(id -> insertIntoMaster(id))
    .thenCompose(primaryId -> insertIntoChildDB(primaryId));

Upvotes: 2

Related Questions