The Future interface

The Future interface provided by JDK is for the asynchronous programming. It has methods that perform the checking of the completion of the data. The result of the computation can be fetched using the get() method. However, the get() method blocks the call, affecting the major concern of the developers to use the asynchronous programming paradigm. It also has the isDone() method to determine whether the computation is completed or not. It helps us in understanding whether the task is terminated normally or aborted due to an error. An implementer of the FutureTask interface can be used by Executor to execute the task.

Let' update code for BookDAO which we discussed earlier using the Future interface as follows:

Public interface BookDAO { 
  public Future<Book> getBook(long ISBN); 
  public Future<List<Book>> findAllBooks(); 
  public Future<List<Book>> findAllBooks(String author); 
} 

Partly, the problem of using the asynchronous system is solved, but not completely.

The Java 1.8 API has provided CompletableFuture as an implementation of Future as well as the CompletionStage interfaces. The CompletionStage interface facilitates the manipulation of status and the result of an ongoing task. The CompletableFuture interface has the callback methods that get invoked on events without blocking. The implementation of the code using CompletableFuture is as follows:

Public interface BookDAO { 
  public CompletableFuture<Book> getBook(long ISBN); 
  public CompletableFuture<List<Book>> findAllBooks(); 
  public CompletableFuture<List<Book>> findAllBooks(String author); 
} 

Here, we have successfully achieved an asynchronous non-blocking call; however, we are still handling the data that needs to be manipulated by the developers. Do we have any better options? Can we use something instead of Collections? Instead of getting multiple calls, can we get a signal per item, a signal on completion of the task, or a signal if the error occurs? Yes, we have the choice given by Java 1.8 as streams.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.1.239