Future interface in java

Future interface introduces in java 1.5 in java. util.concurrent package. It is used to hold the result of an asynchronous computation. The asynchronous result will automatically appear in the Future after the asynchronous process is completed. Mostly Future will use with Callable interface and ExecutorService to capture the asynchronous result. 

Implementation of Future with thread

public class FutureWithThread {
private ExecutorService executor
= Executors.newFixedThreadPool(20);

public Future<Integer> makeDouble(Integer num){
return executor.submit(()->{
Thread.sleep(100);
return num * num;
});
}
}

The interface provides the following four methods:

  1. get(): the method waits for the computation to complete the async operation and waits to retrieve its result.
  2. cancel(): suppose in case we want to stop the execution and we can use the future.cancel(true) to tell the executor service to stop the current operation and interrupt the current thread. if we call get() after cancel() then it will throw CancleException. future. isCancelled () will tell us if the execution is canceled or not. this will help to avoid CancleException.
  3. isCancelled() : tell us if the execution is canceled or not. if execution is canceled then it will return true otherwise it will return false.
  4. isDone():  tell us if execution has been done or not. if execution is done then it will return true otherwise it will return false.

Getting result single thread : 

Future<Integer> future = new FutureWithThread().makeDouble(number);
while (future.isDone()){
log.info("in-progress");
}
Integer doubleNumber = future.get();

Getting result from multiple threads : 

List<Future> futures = new ArrayList<>();
List<Future<Integer>> collect = IntStream.range(0, number).boxed().map(m -> {
return new FutureWithThread().makeDouble(m);
}).collect(Collectors.toList());

return collect.stream().map(m->{
try {
return m.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());


Canceling async operation : 


Future<Integer> integerFuture = new FutureWithThread().makeDouble(number);
integerFuture.cancel(true);
if(integerFuture.isCancelled()){
log.info("Current operation is cancelled");
}


Limitation of future:

  1. It cannot be manually completed :

    Let’s say that you’ve written a function to fetch the latest price of an e-commerce product from a remote API. Since this API call is time-consuming, you’re running it in a separate thread and returning a Future from your function.

    Now, let’s say that If the remote API service is down, then you want to complete the Future manually by the last cached price of the product.

    Can you do this with Future? No!

  2. You cannot perform further action on a Future’s result without blocking:

    Future does not notify you of its completion. It provides a get() method that blocks until the result is available.

    You don’t have the ability to attach a callback function to the Future and have it get called automatically when the Future’s result is available.

  3. Multiple Futures cannot be chained together :

    Sometimes you need to execute a long-running computation and when the computation is done, you need to send its result to another long-running computation, and so on.

    You can not create such an asynchronous workflow with Futures.

  4. You can not combine multiple Futures together :

    Let’s say that you have 10 different Futures that you want to run in parallel and then run some functions after all of them are complete. You can’t do this as well with Future.

  5. No Exception Handling :

    Future API does not have any exception-handling construct.

Comments

Popular posts from this blog

Primitive Data Types in java

Coding Problem 3 - Weather Observation Station 7 [HackerRank - SQL]

Do you know how does 𝙎𝙥𝙧𝙞𝙣𝙜𝘼𝙥𝙥𝙡𝙞𝙘𝙖𝙩𝙞𝙤𝙣.𝙧𝙪𝙣() work internally?