Home > Java > javaTutorial > body text

Java async

WBOY
Release: 2024-08-30 15:09:53
Original
822 people have browsed it

In Java programming language, async is defined as a call or a function which can be defined in another function or passed as arguments in another function which is usually declared when the program needs to be executed without blocking the program, and this is done when the call returns from the event and it returns to the callback function. In java, this is defined as a callback method invoked inside the newly created thread. So, in general, async programming which is nothing but writing a non-blocking code which is the program that is run on a separate thread by notifying the main thread about the performance progress of completion of the thread execution or failure.

Working of async in java

In this article, we will discuss a callback method which is known as the async function in java. This function is also known as await in java. In java, to make or write asynchronous programming by starting a new thread by making it asynchronous themselves. The asynchronous callbacks are used only when the tasks are not dependent on each other, which might take some time for executing. So, in general, the async call can be explained by taking an example of online shopping where when we select some item and add it into the cart, then that item will not be blocked as it will also be available to others too where others don’t need to wait for the order of the item to finish. So, whenever we want to run any program that can be executed without blocking its execution, it is done using async programming.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

In Java, there are many features for writing non-blocking code, such as using threads, futures, streams, etc., as there are many demands for non-blocking code where the async programming is required to execute the code asynchronously. So let us discuss a few ways of how to achieve asynchronous programming such as jcabi aspects, cactoos, guava, completeableFutures, FutureTask, EA Async, etc.

1. completeableFutures

The completeableFutures is the java version of javascript promises known as completeableFutures which can implement two interfaces such as Future and CompletionStage, where a combination of these two interfaces completes this feature for writing or working with async programming. This feature provides many methods such as supplyAsync, runAsync, etc. These methods are used to start the asynchronous part of the code because supplyAsync method is used when we are doing something with the result, and if we do not want anything, we can use the runAsync method. There other different methods in completeableFutures such as thenCompose if we want to use multiple completeableFutures one after one or in simple when we want to use nested completeableFutures and if we want to combine the results of two completeableFutures, then there is a method named thenCombine method. So these all methods are handled in a completable future, which in turn has completion stage methods that hold all these methods.

Sample example: To create completeableFuture using no-arg constructor by the following syntax:

CompleteableFuture <String> completeableFuture = new CompleteableFuture <String>();
Copy after login

So to get the result, we have to use the get() method. So we can write it as

String result = completeableFuture.get()  where this gets () method will block until the Future completes, but this call will block it forever as Future is never completed. So we have to complete it manually by calling the below method.

completeableFuture.complete("Result")
Copy after login

Therefore the clients get specified results ignoring the subsequent calls. The program might look like below.

CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
while (!completableFuture.isDone()) {
System.out.println("CompletableFuture is not finished yet...");
}
long result = completableFuture.get();
Copy after login

2. EA Async

This is another feature in java for writing asynchronous code sequentially, which naturally provides easy programming and scales. This is Electronic Arts which got the async-await feature which is given to the java ecosystem through this ea-async library. This feature converts the runtime code and rewrites the call to await method, which works similarly as completableFuture. So we can implement the above completeableFuture code by using the EA-sync method known as the await method by making a call to the Async.init method for initializing Async runtime.

So let us consider an example of factorial of a number using both completeableFuture and EA sync.

CompletableFuture <Double> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
while (!completableFuture.isDone()) {
System.out.println("The completeableFuture is not completed...");
}
double res = completableFuture.get();
Copy after login

So the above code can be used in the EA sync feature using the await method for the above code; instead of get() method, we use the await() method so the above code can be updated with only the last line and we have to initialize by init method of Async in the static block the rest of the code remains same.

static { Async.init(); }
public func_name(){….. same as above code of completeableFuture…
double res Async.await(completableFuture);
Copy after login

From the above sample code, which is transformed code of completeableFuture code by using static block also for initializing the Async runtime so that the Async can transform the code of completeableFuture code during runtime and then to the await method, it can rewrite the calls which will now EA async will behave similarly to that of using the chain of completeableFuture or Future.join method. So now, when once the asynchronous execution of any method is completed, then the result from the Future method is passed to another method where the method is having the last execution using the CompleteableFuture.runAsync method.

In Java, as discussed above, there are many different ways for writing the asynchronous programming using various other methods.

Conclusion

In this article, we discussed java async where it is defined as a callback method that will continue the execution of the program without blocking by returning the calls to the callback function. This article saw how asynchronous programming is written in java using different features such as CompleteableFutures, EA async, Future Task, Guava, etc. In this article, we have seen two among these features for making the callback functions asynchronous by using various methods provided by the given respective features.

The above is the detailed content of Java async. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!