Month: July 2018
Replication
Neural Networks
Java Multi-Thread
hello
Java – CompletableFuture
CompletableFuture interface is in Java 8 or later, before Java 8 there’s only Future interface.
Future interface provider developers ability to run async tasks. It provides two method: isDone() and get().
- isDone() method returns a boolean value indicates that whether the task run asynchrounsly is completed or not.
- get() method get the value returned from async task once it’s done. This will block the current thread.
The motivation to have completable future is that Future interface is insufficient in the following cases.
- Future interface do not provide functionality to manually complete the async task.
- Future interface do not provide functionality to have callback function, meaning we are not notified when async task finishes, and we cannot do stuff once the async task finishes.
CompletableFuture has many methods to support the above disadvantages. Now let’s look at some most used methods of CompletableFuture.
complete()
With this method, we can manually complete the async task.
CompletableFuture future = new CompletableFuture();
future.complete("Manually complete task.");
CompletableFuture provides us two method to set callback function for async task: supplyAsync() and runAsync(). The different is that supplyAsync() will return value, and runAsync() just run an async task. Let’s look at the code.
supplyAsync()