Skip to main content

Posts

Showing posts with the label Multithreading

Executing chain of tasks sequentially using CompletableFuture

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. 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 furth...