Skip to content

Instantly share code, notes, and snippets.

@viveknaskar
Last active September 20, 2022 21:39
Show Gist options
  • Save viveknaskar/9b7857e76fa842d42e3ba33a734a3d10 to your computer and use it in GitHub Desktop.
Save viveknaskar/9b7857e76fa842d42e3ba33a734a3d10 to your computer and use it in GitHub Desktop.
Simple Illustration of thenApply method for CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class ThenApplyExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
// delaying the thread by 2 seconds
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "World";
}).thenApply(name -> "Hello " + name); // Attaching a callback to the Future
// get() blocks and gets the result of the Future
System.out.println(completableFuture.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment