Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to create an already-completed CompletableFuture<Void>

I am using Completable futures in java 8 and I want to write a method that, based on a received parameter, either runs multiple tasks with side effects in parallel and then return their "combined" future (using CompletableFuture.allOf()), or does nothing and returns an already-completed future.

However, allOf returns a CompletableFuture<Void>:

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) 

And the only way to create an already-completed future that know is using completedFuture(), which expects a value:

public static <U> CompletableFuture<U> completedFuture(U value) 

Returns a new CompletableFuture that is already completed with the given value.

and Void is uninstantiable, so I need another way to create an already-completed future of type CompletableFuture<Void>.

What is the best way to do this?

like image 362
Roy Menczer Avatar asked Oct 09 '17 08:10

Roy Menczer


People also ask

What is CompletableFuture void?

CompletableFuture<Void> : The Void tells the user there is no result to be expected.

Can CompletableFuture be reused?

What you describe is not a “reuse” of a CompleteableFuture , as it still performs only one action and completes at most once. You are just registering multiple dependent stages, which is completely within the foreseen usage.

Can CompletableFuture be null?

Since Void can not be instantiated, you can only complete a CompletableFuture<Void> with a null result, which is exactly what you also will get when calling join() on the future returned by allOf() once it has been successfully completed. CompletableFuture<Void> cf = CompletableFuture.


2 Answers

Since Void can not be instantiated, you can only complete a CompletableFuture<Void> with a null result, which is exactly what you also will get when calling join() on the future returned by allOf() once it has been successfully completed.

So you can use

CompletableFuture<Void> cf = CompletableFuture.completedFuture(null); 

to get such an already completed future.

But you can also use

CompletableFuture<Void> cf = CompletableFuture.allOf(); 

to denote that there are no jobs the result depends on. The result will be exactly the same.

like image 79
Holger Avatar answered Sep 18 '22 14:09

Holger


pass a null I guess:

CompletableFuture<Void> done = CompletableFuture.completedFuture(null); 
like image 36
Eugene Avatar answered Sep 17 '22 14:09

Eugene