Asynchronous Programming in Java
Last Updated :
17 Dec, 2023
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:
- Callbacks with CompletableFuture
- 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.
Example of demonstrating the use of the CompletableFuture:
Java
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
- 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.
Below is a basic example is mentioned below:
Java
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!
Share your thoughts in the comments
Please Login to comment...