Sobes.tech
Junior — Middle

When does the asynchronous operation start when using CompletableFuture in Java?

sobes.tech AI

Answer from AI

The launch of an asynchronous operation in CompletableFuture in Java depends on how the object is created:

  • If you use methods like CompletableFuture.supplyAsync() or runAsync(), the asynchronous operation starts immediately after calling these methods, usually in a separate thread from the pool.

  • If you create a CompletableFuture manually and then call chain methods (thenApply, thenCompose, etc.), execution begins when the method initiating the asynchronous work is called (for example, supplyAsync).

Thus, the launch occurs at the moment of creating the CompletableFuture via asynchronous factory methods. If an empty CompletableFuture is created and then completed manually, the operation starts when the corresponding methods are called.

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // This code runs immediately in another thread
    return "result";
});