Completable futures in java 8

 A CompletableFuture is a class in Java that belongs to the java.util.concurrent package.

It is used for asynchronous computation. The code is executed as a non-blocking call in a separate thread, and the result is made available when it is ready.

By doing this, the main thread does not block/wait for the completion of the task, and it can execute other tasks in parallel.


sample code:

public class CompletableFutures {
public static void main(String[] args) {

ExecutorService service = Executors.newFixedThreadPool(10);
ExecutorService service1 = Executors.newCachedThreadPool();
int n = 0;

while (n < 10) {
CompletableFuture.supplyAsync(() -> product(1), service1)
.thenApplyAsync(a -> order(a), service1)
.thenApplyAsync(a -> pay(a), service1)
.thenApplyAsync(a -> sendMail(a), service1);
n++;
}

}

static int product(Integer a) {
System.out.println(a + " current thread name: " + Thread.currentThread().getName() + " method name: " + new Object() {
}.getClass().getEnclosingMethod().getName());
return 1;
}

static int order(Integer a) {
System.out.println(a + " current thread name: " + Thread.currentThread().getName() + " method name: " + new Object() {
}.getClass().getEnclosingMethod().getName());
return 2;
}

static int pay(Integer a) {
System.out.println(a + " current thread name: " + Thread.currentThread().getName() + " method name: " + new Object() {
}.getClass().getEnclosingMethod().getName());
return 3;
}

static int sendMail(Integer a) {
System.out.println(a + " current thread name: " + Thread.currentThread().getName() + " method name: " + new Object() {
}.getClass().getEnclosingMethod().getName());
return 4;
}

}

Comments

Popular posts from this blog

Understanding and Avoiding Race Conditions in Java

The Interplay of Money and Risk

For Java