ConfusionableFuture in Java8

Code, Software June 9th, 2015

We are making use of Java 8’s CompleteableFuture but I was getting very confused about what the difference between thenCompose, thenAccept and thenApply. Thankfully I work with smart people. Here is our discussion.

lw: It’s really simple…
thenCompose takes two promise actions and runs one after the other
e.g.

readContentsFromAFile().thenCompose(contents -> doSomethingElse(contents))

would read the contents of a file then do something else, all async

me: where the `printContentsToScreen` returns a promise
lw: Yeah

lw: thenApply takes a promise action and a pure function and transforms the output of the promise using that function

readContentsFromAFile().thenApply(contents -> length(contents))

That makes a new promise action that reads the contents of a file and returns the length of it (notice there is only one promise action involved)

thenAccept takes a promise action and a non-promise procedure and runs the procedure non-async on the results e.g.

readContentsFromAFile().thenAccept(contents -> blockingPrintContentsToScreen(contents))

That makes a new promise action that reads the contents from a file asynchronously, then run the blocking print operation on the contents
The main point is that thenAccept only executes one promise then a normal java procedure

me: So

CompletableFuture<int> cf = readContentsFromAFile().thenApply(contents -> length(contents)); 

lw: Correct

me: Where as thenAccept returns CompletableFuture<void>

lw: Yes

me: and thenCompose is like `here, use this one`
So it’s like

CompletableFuture<Whatever> cf = something.thenCompose(contents -> asyncGetWhatever());

lw: Yeh. I prefer to think of `thenCompose` as chaining two promises together, so when the first one finishes it runs the next one

me: Got it, thanks.

Leave a Reply