St.Antario St.Antario - 1 month ago 4
Java Question

Understanding CompletableFuture::runAsync

I just read the documentation about

CompletableFuture::runAsync
and was pretty confused by the explanation. Here is what's written there:


Returns a new
CompletableFuture
that is asynchronously completed by a
task running in the given executor after it runs the given action.


As far as I understand it,
CompletableFuture
looks like
Future
with that it can "register" some sort of callbacks and invoke them implicitly once a given action is finished.

Taking that into account, let's consider the following code:

ExecutorService threadsPool;
Runnable r;
//...
CompletableFuture.runAsync(r, threadsPool);


In this code we register the
Runnable
to be executed asynchronously in the given
ThreadPool
.

But what does it mean
CompletableFuture
that is asynchronously completed by a task
. How can the task make the
CompletableFuture
become completed... ? It doesn't make much sense to me.

Answer

Inside CompletableFuture there is the following code called by runAsync.

static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
    if (f == null) throw new NullPointerException();
    CompletableFuture<Void> d = new CompletableFuture<Void>();
    e.execute(new AsyncRun(d, f));
    return d;
}

AsyncRun is the asynchronously executed task that will, after running the Runnable f, complete the CompletableFuture d asynchronously. I won't bother with the code here because it's not very informative, and it just performs the completion of d by calling its postComplete() method (the package-private one).