Skip to main content

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

The Great Minds

🔬 Science & Philosophy Carl Sagan – astrophysicist, science communicator ( Cosmos ). Richard Dawkins – evolutionary biologist ( The Selfish Gene ). Neil deGrasse Tyson – astrophysicist, communicator ( Astrophysics for People in a Hurry ). Brian Cox – physicist, popular science communicator. 💰 Business, Investing & Strategy Warren Buffett – value investing, Berkshire Hathaway. Charlie Munger – Buffett’s partner, multidisciplinary wisdom. Naval Ravikant – angel investor, modern philosopher ( The Almanack of Naval Ravikant ). Peter Lynch – legendary investor ( One Up on Wall Street ). Steve Jobs – Apple co-founder, master of design and vision. Elon Musk – Tesla, SpaceX, futurist entrepreneur. Richard Dawkins

The Paradox of Abundance

Why having more can make you weaker — and having less can make you stronger.