CompletableFuture
CompletableFuture was introduced in Java 8 to support the asynchronous execution and avoid blocking calls. It implements Future and CompletionStage interfaces. Future can be used to retrieve the value and status of current task while CompletionStage provides multiple methods to support the event based task execution which helps in creating a chain or pipeline for the actions to happen during specified events.Runnable
Runnable interface has a void run() method where we can write the logic which we want to execute but it can not return any result. Runnable can be executed using Thread or ExecutorService.
public abstract void run();When we need to execute some tasks where we don't need to wait to get some result back then we can use Runnable. We just execute our task and do other work as we don't depend on the result of the task. Like if we want to write some logs asynchronously then we can use Runnable interface and execute without waiting for it's completion. Even Callable also can be used for same purpose.
Callable
Callable has call() method which can return a result and can throw exception also. Callable can be executed using ExecutorService.V call() throws Exception;When we need to perform some task after one task's completion then this task depends upon the result of another tasks. In this scenario we can use Callable as it returns a result which we can pass to dependent task to start with. Like similar to producer/consumer problem where consumer waits for producer to complete so it can utilise the produced value to consume.
When callable is submitted for execution to ExecutorService, it returns instance of Future<V> with generic value.
Future
Future provides several method to get the status of current Callable task. Also it can be used to cancel the task or get the result of task upon completion. We can call the get() method to get the result of Callable task but it will block the execution and no other code will execute until the task is completed which behaves like synchronous execution.Problem
Usage scenario
Now we will define a problem to solve it using Future and CompletableFuture.Suppose we have a file which contains some numbers on each line. We need to find out the largest number in one thread from this file and then print it to the console in another thread.
Solution
If we break the problem then it looks like some supplier consumer problem where one thread is supplying the largest number and another thread print it to console. Below is our coding solution which depicts this behaviour and tries to solve the problem in two different ways using Future and CompletableFuture.Supplier code
Below is the code for supplier which reads the file and gives largest number. We use the same supplier code for both the cases (Future & CompletableFuture).private Supplier<Integer> findLargestNum()throws Exception{ System.out.println("findLargestNum: start"); return ()->{ Integer result = null; try { result = Files.readAllLines(Paths.get(Thread.currentThread() .getContextClassLoader() .getResource("numbers.txt").toURI())) .stream() .filter(s->{return s!=null && s.length()>0;}) .mapToInt(s->Integer.parseInt(s)) .max().orElse(0); } catch (Exception e) { e.printStackTrace(); } System.out.println("findLargestNum: end"); return result; }; }
Using Callable and Future (Blocking)
Now will see how it works with Callable and Future. Here I have put S.O.P. statements to see the ordering of execution. Here we can see that "maxNumFut.get()" is making blocking call which will not let the further lines execute until the tread is complete.System.out.println("testCallable: start"); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Integer> maxNumFut = executor.submit(()->{ return findLargestNum().get();//calling get on supplier to execute the supplier code }); Integer maxNum = maxNumFut.get();//blocking call executor.execute(()->{ System.out.println("print: start"); System.out.println(maxNum); System.out.println("print: end"); }); System.out.println("testCallable: end");Below is the output of the above code. If you notice here that the S.O.P. highlighted in bold are from the code where it reads the file and finds largest number. This block has executed in synchronous way and has blocked the execution of other code otherwise you might have seen that "testCallable: end" statement could have been printed earlier.
testCallable: start
findLargestNum: start
findLargestNum: end
testCallable: end
print: start
334556
print: end
Using CompletableFuture (Non-Blocking)
With CompletableFuture it is very easy to create the chain of tasks which execute in specified order asynchronously which we will see in below code.System.out.println("testCompletable: start"); CompletableFuture.supplyAsync(findLargestNum()) .thenAccept((s->{ System.out.println("print: start"); System.out.println(s); System.out.println("print: end"); })); System.out.println("testCompletable: end");
In above code at line#2 we used "supplyAsync" which takes a supplier and executes asynchronously using fork join pool and returns an instance of CompletableFuture. Then we have called "thenAccept" which takes a consumer and can access the output of previous task. We have provided consumer as lambda expression here where "s" is the output from previous task's output.
Now see the below output of above code where it shows the non-blocking execution.
testCompletable: start
findLargestNum: start
testCompletable: end
findLargestNum: end
print: start
334556
print: end
If you notice the line#3 is coming between the supplier code execution which provide it to be non-blocking. CompletableFutrue provides many methods to build this asynchronous chain of tasks, for example:-
CompletableFutrue.suplyAsync(....)
.thenApplyAsync(...)
.thenApplyAsync(...)
.thenAccept(...)
Below are few lines from "numbers.txt" which I have used to read the numbers from.
22
34
234
52
223
11
24
2
42
323
232
....
If you interested then you can check my other post on sequential executions: https://www.thetechnojournals.com/2019/11/executing-chain-of-tasks-sequentially.html
Comments
Post a Comment