Is there a way to delay the execution of the completable future?

lazyloader :

I'll be using CompletableFuture for my async calls. I would like to know if there's a way to delay its execution. I have around 5 async calls for one flow, and I am chaining then using thenApply/thenCompose as required. My problem is when I create the first CF for a call, it'll start executing whenever a thread is free. I want that first all my tasks should be chained, then when I call , say complete(), it starts executing. What I am looking for is something similar to the intermediate operations in Java streams. I had some help regarding this in one of my earlier questions on SO, but it's not solving my purpose.

My tech stack only allows Java 8, so can't use any features launched in the next versions.

Tobias :

I can't write comments yet, so I cannot ask for clarification. Please forgive me, if I didn't understand correctly, what you need. From what I can tell, you're basically just looking for a way to delay the execution of a CompletableFuture until you are ready to do so.

Have you considered giving another CF as parameter to the function you want to call? Once you are ready, just complete this CF and then the function gets executed. It goes somewhat like this:

CompletableFuture<Void> setup = new CompletableFuture<>();
delayedFunction(setup);

//do whatever you want
System.out.println("foo");

//once you are ready, complete setup to execute the delayed function
setup.complete(null);


public static CompletableFuture<Void> delayedFunction(CompletableFuture<Void> setup) {
  return setup.
    thenAccept(v-> {
      System.out.println("bar");
    });
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147791&siteId=1