Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to complete a CompletableFuture<Void>?

Tags:

I want a CompletableFuture that only signals the completion (e.g. I don't have a return value).

I can instantiate the CompletableFuture as:

CompletableFuture<Void> future = new CompletableFuture<> (); 

But what should I feed into the complete method? For example, I can't do

future.complete(new Void()); 
like image 326
Xinchao Avatar asked Dec 20 '17 05:12

Xinchao


People also ask

What is CompletableFuture void?

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

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.

How do you return a void in Java?

You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.

How does CompletableFuture work in Java?

What is CompletableFuture? A CompltableFuture is used for asynchronous programming. Asynchronous programming means writing non-blocking code. It runs a task on a separate thread than the main application thread and notifies the main thread about its progress, completion or failure.


1 Answers

As you've noticed, you cannot instantiate a Void object like this. Since you don't care about the future's value, you could just complete it with null:

future.complete(null); 
like image 136
Mureinik Avatar answered Sep 25 '22 09:09

Mureinik