Skip to main content

Asynchronicity

Approaches for Asynchronous Programming

There are two commonly used approaches for Asynchronous Programming as mentioned below:

1. Callbacks with CompletableFuture

2. Asynchronous Programming with Future and ExecutorService

1. Callbacks with CompletableFuture

  • The CompletableFuture is a class introduced in Java 8 that facilitates asynchronous programming using the callback-based approach.
  • It represents a promise that may be asynchronously completed with the value or an exception.
//Java program to demonstrate the use of the CompletableFuture
import java.io.*;
import java.util.concurrent.CompletableFuture;

public class CF {

public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello, CompletableFuture!";
});
future.thenAccept(result -> System.out.println("The Result: " + result));
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Output

The Result: Hello, CompletableFuture!

2. Asynchronous Programming with Future and ExecutorService

  • The Future and ExecutorService can be used for the asynchronous programming in a more traditional way.
  • The ExecutorService allows you to submit tasks for the asynchronous execution.
//Java program to demonstrate Asynchronous
// Programming with Future and ExecutorService
import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FE {

public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello, Future!";
});
try {
String result = future.get();
System.out.println("The Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
executor.shutdown();
}
}

Output

The Result: Hello, Future!