简体   繁体   中英

Java 11 : Cycle execute CompletableFuture

I'm looking a way to cycle CompletableFuture. Suppose I have

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hi");
 
future.thenApplyAsync(result -> {
    System.out.println(result + " all"); //output Hi all
    return result;
})

And I want to repeat this chain after it finished until I call cancel(). Is it possible? I can recreate this chain again in a for loop but it seems to be an ugly solution.

Consider using ScheduledExecutorService , for instance scheduleWithFixedDelay() . You can put the logic executed by the current Future to the Runnable . If you don't needed any delay, you can set it to 0. From implementations I'd suggest to consider first the ScheduledThreadPoolExecutor . If you want, you can override shutdown() and implement the desired shuddown logic.

Thanks to mentallurg who provided a hint, I have developed the following solution

public class CombinedOperationsBuilder {
    public static <T> CompletableFuture<Void> transformToCycled(Supplier<CompletableFuture<T>> op)
    {
        return CompletableFuture.runAsync(() -> {
            for (;;) {
                try {
                    op.get().get();
                }catch (ExecutionException|InterruptedException e) {
                }
            }
        });
    }
}

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