Future vs CompletableFuture classes in Java

The Future and CompletableFuture classes in Java both represent asynchronous computations, but they have some differences in terms of functionality and usage.

Future:

 Future<ResultType> future = executorService.submit(Callable<ResultType> task);
Enter fullscreen mode
Exit fullscreen mode
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<String> future = executor.submit(() -> { Thread.sleep(2000); // Simulate a time-consuming task return "Hello, from Future!";
});
String result = future.get(); // Blocking call to get the result
System.out.println(result);
executor.shutdown(); 
Enter fullscreen mode
Exit fullscreen mode

CompletableFuture:

 CompletableFuture<ResultType> future = CompletableFuture.supplyAsync(Supplier<ResultType> supplier); 
Enter fullscreen mode
Exit fullscreen mode
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); // Simulate a time-consuming task } catch (InterruptedException e) { e.printStackTrace(); } return "Hello, from CompletableFuture!";
});
future.thenAccept(result -> System.out.println(result)); // Non-blocking callback 
Enter fullscreen mode
Exit fullscreen mode
  • Differences:
  1. Completion Handling: Future relies on blocking methods like get() for result retrieval, while CompletableFuture provides non-blocking methods like thenAccept() for completion handling.
  2. Composition:
    CompletableFuture supports fluent API and allows chaining of multiple asynchronous operations, whereas Future does not.
  3. Explicit Completion:
    CompletableFuture allows explicit completion via methods like complete() or completeExceptionally(), which can be useful in certain scenarios.

Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Ultimately, choosing overlaxed cloud computing for your server needs means opting for a partner that prioritizes your success. Please set api key.