How to Asynchronously Call a Method in Java
-
Use
Thread
to Asynchronously Call a Method in Java -
Use
FutureTask
to Asynchronously Call a Method in Java -
Use
CompletableFuture
to Asynchronously Call a Method in Java -
Use
EA Async
to Asynchronously Call a Method in Java - Use Cactoos Library to Asynchronously Call a Method in Java
In this article, we’ll learn how to call a function in Java asynchronously.
To start, we’ll look at some of Java’s built-in asynchronous programming tools, such as FutureTask and CompletableFuture. Then we’ll look at some libraries offering out-of-the-box solutions, such as EA Async and Cactoos.
Use Thread
to Asynchronously Call a Method in Java
We can begin a new thread to conduct any asynchronous action. It’s more straightforward to understand.
Let’s make a new thread that adds two integers and prints the result:
class example {
public static void main(String[] args) {
int num1 = 4;
int num2 = 5;
int result = num1 + num2;
Thread T = new Thread(
() -> { System.out.println("Addition of " + num1 + " and " + num2 + " is " + result); });
T.start();
}
}
Use FutureTask
to Asynchronously Call a Method in Java
The Future interface allows you to perform asynchronous actions using the FutureTask
. We may use the submit method of the ExecutorService
to run the project asynchronously and return a FutureTask
object.
For example, here is how to find the factorial of a number:
int num1 = 9;
ExecutorService tp = Executors.newCachedThreadPool();
Future<double> futureTask = tp.submit(() -> factorial(num1));
while (!futureTask.isDone()) {
System.out.println("Still processing the task");
}
double result = futureTask.get();
tp.shutdown();
We’ve utilized the Future interface’s isDone
function to see if the job has been finished. After that, we used the get
method to acquire the result.
Use CompletableFuture
to Asynchronously Call a Method in Java
As a hybrid of Future
and CompletionStage
, CompletableFuture
was introduced in Java 8. It has asynchronous programming techniques such as supplyAsync
, runAsync
, and thenApplyAsync
.
A CompletionStage
is a promise. It guarantees that the computation will be completed at some point.
The CompletionStage
is useful because it provides several methods for attaching callbacks to be executed when the stage is completed.
Let’s start from the beginning and make a simple asynchronous calculation.
Use supplyAsync
With CompletableFuture
to Asynchronously Call a Method in Java
CompletableFuture.supplyAsync(this::sendMsg);
As simple as that, the supplyAsync
function accepts a supplier that contains the asynchronous code. We wish to use the sendMsg
function in this example.
Use thenAccept
With CompletableFuture
to Asynchronously Call a Method in Java
CompletableFuture.supplyAsync(this::sendMsg).thenAccept(this::notify);
In the first example, we executed sendMsg
to send a message asynchronously. So let’s add a callback that will alert us of the message’s delivery status.
A callback may be introduced in several ways; one way is to use thenAccept
. It requires a user to be notified, in this example, to handle the result of the preceding computation once done.
Use EA Async
to Asynchronously Call a Method in Java
Here’s another feature of Java that allows you to write asynchronous code stepwise, making programming and scaling much easier. Electronic Arts are the creator of the async-await functionality, which is available to the Java environment via the ea-async package.
This feature transforms the runtime code and rewrites the await method call, comparable to completeableFuture
.
So we can use the EA-sync
method known as the await method to implement the above completeableFuture
code by calling the Async.init
function to initialize the Async
runtime.
Here, we’ll use the await function offered by EA’s Async
class to modify the previously described CompletableFuture
code:
static {
Async.init();
}
To set up the Async
runtime analysis, we use the Async.init
function as static.
public double example2(int num1) {
CompletableFuture<double> cf = CompletableFuture.supplyAsync(() -> factorial(num1));
double result = Async.await(cf);
}
At runtime, the async
function changes the code and rewrites the await
method call to operate similarly, utilizing a chain of CompletableFuture
.
Use Cactoos Library to Asynchronously Call a Method in Java
For asynchronous tasks, this library offers an Async
class. The Cactoos library has an extensive repertoire, ranging from text manipulation to data structures.
This library’s primitive types and functions are comparable to those supplied by other libraries such as Guava and Apache Commons, although they are more focused on object-oriented design concepts.
Here, using an instance of Cactoos’ Async
class, we’ll find the factorial of a number.
Async<Integer, Double> a = new Async<Integer, Double>(inputdata -> factorial(inputdata));
Future<Double> asyncFuture = a.apply(num1);
Double result = asyncFuture.get();
The apply
function uses the ExecutorService.submit
method to act and return a Future interface object. The Cactoos library offers classes that perform the same functions as the static methods found in the Apache Commons library.
I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.
LinkedIn