Here we are going to see how to create a chain of tasks using CompletableFuture and then execute them in sequence one by one.
Our task is to have a number in a loop and then send it two CompletableFuture chain to process each number in two tasks, for example methodA() & methodB() where number is passed to methodA() and then output of it is passed to methodB(). Like this we will create a chain which will execute in the same order it has created.
There are many ways to solve this problem. We will see two different approaches to solve the problem with CompletableFuture.
Our task is to have a number in a loop and then send it two CompletableFuture chain to process each number in two tasks, for example methodA() & methodB() where number is passed to methodA() and then output of it is passed to methodB(). Like this we will create a chain which will execute in the same order it has created.
Common methods
Below are common method which will be used as execution of the tasks.Integer methA(int seq) { System.out.println("A-"+seq); return seq; } Integer methB(int seq) { System.out.println("B-"+seq); return seq; }
There are many ways to solve this problem. We will see two different approaches to solve the problem with CompletableFuture.
Using chain of thenApply()
In this approach we will create a single CompletableFuture and then we will keep adding further tasks for chain by calling the "thenApply()" method on same CompletableFuture instance. Finally we will call the "thenAccept()" on it outside of "For loop" to print the thread completion. Below code shows the implementation for the same.void testWithChain() { CompletableFuture<Integer> ft = null; for(int a=0;a<10;a++) { final int seq = a; if(ft==null) { ft = CompletableFuture.supplyAsync(()->methA(seq)) .thenApply(s->methB(s)); }else { ft.thenApply(s->methA(seq)) .thenApply(s->methB(s)); } } ft.thenAccept(s->System.out.println("Thread completed...")); }
Output
When execute above code, we will see the below output where all execution happened sequentially.
Main started: A-0 B-0 A-1 B-1 A-2 B-2 A-3 B-3 A-4 B-4 A-5 B-5 A-6 B-6 A-7 B-7 A-8 B-8 A-9 B-9 Thread completed... Main ended:
Using Join()
We will create new CompletableFuture for each set of tasks and then apply join() on each.void testWithJoin() { for(int a=0;a<10;a++) { final int seq = a; CompletableFuture.supplyAsync(()->methA(seq)) .thenApply(s->methB(s)) .join(); } }
Output
After executing the above code we will see the similar output to the previous approach.Main started: A-0 B-0 A-1 B-1 A-2 B-2 A-3 B-3 A-4 B-4 A-5 B-5 A-6 B-6 A-7 B-7 A-8 B-8 A-9 B-9 Main ended:
Comments
Post a Comment