Manjunath B Walikar
Manjunath B Walikar

Reputation: 9

java 8, CompletableFuture

In the below code snippet, can anyone let me know what happens when we invoke CompletableFuture.supplyAsync() and when a value is returned will it be returned in a separate thread?

// Run a task specified by a Supplier object asynchronously
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
    @Override
    public String get() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        return "Result of the asynchronous computation";
    }
});

// Block and get the result of the Future
String result = future.get();
System.out.println(result);

Upvotes: 0

Views: 100

Answers (1)

Saurav Kumar Singh
Saurav Kumar Singh

Reputation: 1468

This returns a new Completable Future object which basically get executed in a new thread borrowed from ForkJoinPool. Please refer to javadoc -

/**
 * Returns a new CompletableFuture that is asynchronously completed
 * by a task running in the {@link ForkJoinPool#commonPool()} with
 * the value obtained by calling the given Supplier.
 *
 * @param supplier a function returning the value to be used
 * to complete the returned CompletableFuture
 * @param <U> the function's return type
 * @return the new CompletableFuture
 */
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
    return asyncSupplyStage(asyncPool, supplier);
}

Upvotes: 1

Related Questions