Completable Future: The Promises of Java
During an interview with one of the famous banks in the US, there was a question from the interviewer asking me to optimize a solution which was making 5 API calls sequentially with each call taking more than 200 ms to respond. As a java developer, I was very well able to identify the bottlenecks and I proposed to solution to make all the API calls parallel using the asynchronous approach with the help of ExecutorServices. The interviewer wasn't much convinced with the answer though the proposed solution would have still solved the problem.
The Optimized Solution
The promise would accept two functions: resolve & reject namely and in case of successful completion, the resolve function gets called and reject when there is an error. A series of promises can all be chained to using the 'then' keyword and in situations where there are exceptions, we can have a catch block just like how you would handle exceptions. The basic syntax of promises is given below.
However, in order to understand completable futures fully, one should have a basic understanding of Functional Interfaces and lambda expressions in java.