简体   繁体   中英

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM