- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Differences between CompletableFuture and Future in Java 9?
CompletableFuture<T> class implements Future<T> interface in Java. CompletableFuture can be used as a Future that has explicitly completed. The Future interface doesn’t provide a lot of features, we need to get the result of asynchronous computation using the get() method, which is blocked, so there is no scope to run multiple dependent tasks in a non-blocking fashion whereas CompleteFuture class can provide the functionality to chain multiple dependent tasks that run asynchronously, so we can create a chain of tasks where the next task is triggered when the result of the current task is available.
Syntax
public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T>
Example
import java.util.function.Supplier; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureTest { public static void main(String args[]) throws ExecutionException, InterruptedException { Calculator calc = new Calculator(4, 7); CompletableFuture<Integer> future = CompletableFuture.supplyAsync(calc); future.thenAccept(result -> { System.out.println(result); }); System.out.println("CompletableFutureTest End.... "); Thread.sleep(10000); } } // Calculator class class Calculator implements Supplier<Integer> { private int x, y; public Calculator(int x, int y) { this.x = x; this.y = y; } @Override public Integer get() { try { Thread.sleep(3000); } catch(InterruptedException e) { e.printStackTrace(); } return x + y; } }
Output
CompletableFutureTest End.... 11
Advertisements
To Continue Learning Please Login
Login with Google