简体   繁体   中英

How to trick CompletableFuture.complete() to run dependents/stages in other thread?

CompletableFuture<Object> cf = new CompletableFuture<>();
cf.whenComplete((t, throwable) -> {
    System.out.println(Thread.currentThread().toString());
});
cf.complete(new Object());

This will run whenComplete's BiConsumer callback in the thread calling cf.complete()

How can I run this whenComplete/other lambdas not in the current thread ( commonPool() ?), while not calling cf.complete() from the other thread?

you cannot do this in cd.complete() level. The only way is to use

cd.whenCompleteAsync()

and pass an executor as second parameter.

So it will look like this:

Executor executor = Executors.newSingleThreadExecutor();
CompletableFuture<Object> cf = new CompletableFuture<>();
cf.whenCompleteAsync((t, throwable) -> {
    System.out.println(Thread.currentThread().toString());
}, executor);
cf.complete(new Object());

EDIT: I forgot to mention that you don't have to create your own executor if you don't want. You can simply use whenCompleteAsync() without the second argument. Then it will run the code in ForkJoin pool's thread.

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