Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between thenAccept and thenApply

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?

like image 338
Anqi Lu Avatar asked Jul 18 '17 18:07

Anqi Lu


People also ask

What is difference between thenApply and thenCompose?

thenApply is the map and thenCompose is the flatMap of CompletableFuture . You use thenCompose to avoid having CompletableFuture<CompletableFuture<..>> .

What is thenAccept?

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.

Is thenAccept blocked?

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 is a Completable future?

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.


2 Answers

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.

like image 126
the8472 Avatar answered Oct 01 '22 12:10

the8472


thenApply returns result of curent stage whereas thenAccept does not.

Read this article: http://codeflex.co/java-multithreading-completablefuture-explained/

CompletableFuture methods

like image 26
ybonda Avatar answered Oct 01 '22 12:10

ybonda