St.Antario St.Antario - 6 months ago 32
Java Question

Understanding CompletableFuture::runAsync

I just read the documentation about

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

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

As far as I understand it,
looks like
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
to be executed asynchronously in the given

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


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).