We can use CompletableFuture for asynchronous programming
which in a non-blocking code. Other than the running main thread, it is used to
run a task on a separate thread. Paralleling threads running will avoid the
main thread to block or wait the separate thread for task performing until
completing. Parallelism thoroughly improve performance of a application.
The most frequently used CompletableFuture methods are:
1.
supplyAsync(): It complete its job
asynchronously. The result of supplier is run by a task from
ForkJoinPool.commonPool() as default. The supplyAsync() method returns
CompletableFuture on which we can apply other methods.
2.
thenApply(): The method accepts function as
an arguments. It returns a new CompletableStage when this stage completes
normally. The new stage use as the argument to the supplied function.
3.
join(): the method returns the result value
when complete. It also throws a CompletionException (unchecked exception) if
completed exceptionally.
Example
