Class CompletableFutureBasicsExample

java.lang.Object
modernfeatures.concurrency.CompletableFutureBasicsExample

public class CompletableFutureBasicsExample extends Object

Demonstrates basic usage of CompletableFuture for asynchronous programming in Java 8+.

  • Run asynchronous tasks that return a result using CompletableFuture.supplyAsync().
  • Run asynchronous tasks without a result using CompletableFuture.runAsync().
  • Block and wait for asynchronous computations to complete using get().

Example usage:

 
 CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
     // Long-running computation
     Thread.sleep(10000);
     return "Hello from CompletableFuture!";
 });
 String result = future.get();
 System.out.println("Result: " + result);
 
 
  • Constructor Details

    • CompletableFutureBasicsExample

      public CompletableFutureBasicsExample()
  • Method Details

    • main

      public static void main(String[] args) throws ExecutionException, InterruptedException

      Main method demonstrating basic CompletableFuture usage.

      • Starts an asynchronous task that returns a result.
      • Starts an asynchronous task without a result.
      • Blocks the main thread to wait for completion of both tasks.
      Parameters:
      args - command line arguments (not used)
      Throws:
      ExecutionException - if the computation threw an exception
      InterruptedException - if the current thread was interrupted while waiting