I'm reading the document on CompletableFuture
and The description for thenAccept()
is
Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied action.
and for thenApply()
is
Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied function.```
Can anyone explain the difference between the two with some simple examples?
thenApply is the map and thenCompose is the flatMap of CompletableFuture . You use thenCompose to avoid having CompletableFuture<CompletableFuture<..>> .
thenAccept() is an instance method in Java. It is used when we don't want to return anything from our callback function and only want to run some code once a Future completes. This method has access to the result of the CompletableFuture on which it is attached.
The accept function can block the caller until a connection is present if no pending connections are present on the queue, and the socket is marked as blocking. If the socket is marked as nonblocking and no pending connections are present on the queue, accept returns an error as described in the following.
What's a CompletableFuture? CompletableFuture is used for asynchronous programming in Java. Asynchronous programming is a means of writing non-blocking code by running a task on a separate thread than the main application thread and notifying the main thread about its progress, completion or failure.
You need to look at the full method signatures:
CompletableFuture<Void> thenAccept(Consumer<? super T> action) <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
thenAccept
takes a Consumer
and returns a T=Void
CF, i.e. one that does not carry a value, only the completion state.
thenApply
on the other hand takes a Function
and returns a CF carrying the return value of the function.
thenApply
returns result of curent stage whereas thenAccept
does not.
Read this article: http://codeflex.co/java-multithreading-completablefuture-explained/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With