Java – what is the correct way to create a completed completable future

I use completable future in Java 8. I want to write a method to run multiple tasks with side effects in parallel according to the received parameters, and then return their "combined" future (using completable future. Allof()), or do nothing and return to the completed future

However, allof returns completable future < void >:

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

The only way to create a completed future is to use completedfuture(), which requires a value:

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

And void are not realizable, so I need another way to create a future where the completable future < void > type has been completed

What's the best way to do this?

Solution

Since void cannot be instantiated, you can only complete completable future < void > and use null results, which is the result that will be obtained when the future call join() returned by allof() is successfully completed

So you can use

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

Get such a completed future

But you can also use

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

No result depends on your work The results will be exactly the same

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>