Open In App

Asynchronous Programming in Java

Asynchronous programming in Java allows you to execute the tasks concurrently improving the overall performance and responsiveness of your applications. Java provides several mechanisms for asynchronous programming and two commonly used approaches are discussed in this article.

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

Example of demonstrating the use of the CompletableFuture:




//Java program to demonstrate the use of the CompletableFuture
import java.io.*;
import java.util.concurrent.CompletableFuture;
  
public class GFG {
  
    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

Below is a basic example is mentioned below:






//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 GFG {
  
    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!





Article Tags :