Updated July 1, 2023
Introduction to Java async await
Java Asynchronous await is defined as performing I/O bound operations and doesn’t need any application responsiveness. These functions are normally used in file and network operations as they require callbacks executed on operation completion; also that this function always returns a value. With the help of the awake keyword, asynchronous calls are used inside regular control flow statements, and it is a non-blocking code. In this topic, we are going to learn about Java async await.
Syntax
The general signature of async / await is given as
async void test() {
print('Welcome to EDUCBA');
}
The await goes on like
const test=async() =>
{
await test ();
Print ("completed");
}
How does the async-await function work in Java?
Async awaits function helps write synchronous code while performing async tasks behind the code. And we need to have the async keyword. And next is the awaited part that says to run the asynchronous code normally and proceed to the next line of code. The new operator “Await” automatically waits for a promise to resolve the running process when used inside an async function. However, it causes syntax errors when used in any other case.
If the function throws an error in error handling, the async function’s promise will reject. If the respective function happens to return a value, the promise will be solved. This non-blocking code runs on a separate thread and notifies the main thread about its completion or failure of a task. Try-catch is used in a function to handle the errors synchronously. Let’s take a sample beginning like
async function hello() {
//process waiting
await new Promise(res => setTimeout(res, 2000));
// Rejection with 20 %
if (Math.random() > 0.2) {
throw new Error('Check the number.')
}
return 'number';
}
The above code says that the function hello() is async, resolves it by returning a number, and throws an error by checking the number.
Next, using await and return together to suspend a process
async function miss() {
try {
return await hello();
} catch (e) {
return 'error caught';
}
}
Better promising chaining with this function is given as
async function promise1( req,res)
{
try
{
let a=await a.get(req,uid);
let b=await cart.get (yser,uid);
Res.send(await dosome(a,cart));
}
catch (err)
{
res.send(err);
}
}
So here await keyword instructs the function get () to complete before catching an error.
With this Completable future, it returns a future object. This Completable future is a reference to asynchronous computation and implements the future.
private static CompletableFuture<Void> hello{
try {
String intermediate = await(doA());
String res = await(doB(intermediate));
reportSuccess(res);
} catch (Throwable th) {
reportFailure(th);
}
return completedFuture(null);
}
Examples of Java async await
So in this section, we will see how the finer points of async and await work here.
Example #1
Code:
import 'dart:async';
void main() async {
var a = await ten();
print(a);
}
Future<int> ten() async {
return 10;
}
Explanation
The above code uses the future, the Java 7 version API, and waits ten seconds to display 10.
Output:
Example #2
Code:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
class Comput1 implements Runnable
{
public static int item = 0;
public void run()
{
item = 3 * 3;
try
{
CyclicBarrierAwaitExample2.newBarrier.await();
}
catch (InterruptedException | BrokenBarrierException e)
{
e.printStackTrace();
}
}
}
class Comput2 implements Runnable
{
public static int total = 0;
public void run()
{
// check if newBarrier is broken or not
System.out.println("Is it broken? - " + CyclicBarrierAwaitExample2.newBarrier.isBroken());
total = 20 + 20;
try
{
CyclicBarrierAwaitExample2.newBarrier.await(2000, TimeUnit.MILLISECONDS);
System.out.println("Number of rooms waiting at the barrier "+
"here = " + CyclicBarrierAwaitExample2.newBarrier.getNumberWaiting());
}
catch (InterruptedException | BrokenBarrierException e)
{
e.printStackTrace();
}
catch (TimeoutException e)
{
e.printStackTrace();
}
}
}
public class CyclicBarrierAwaitExample2 implements Runnable
{
public static CyclicBarrier newBarrier = new CyclicBarrier(3);
public static void main(String[] args)
{
CyclicBarrierAwaitExample2 test = new CyclicBarrierAwaitExample2();
Thread t = new Thread(test);
t.start();
}
@Override
public void run()
{
System.out.println("Number of parties required to trip the barrier = "+
newBarrier.getParties());
System.out.println("Sum of product and sum = " + (Comput1.item +
Comput2.total));
Comput1 comp1 = new Comput1();
Comput2 comp2 = new Comput2();
Thread t = new Thread(comp1);
Thread t2 = new Thread(comp2);
t.start();
t2.start();
TimeUnit unit = TimeUnit.SECONDS;
try
{
CyclicBarrierAwaitExample2.newBarrier.await(1,unit);
}
catch (InterruptedException | BrokenBarrierException | TimeoutException e)
{
e.printStackTrace();
}
System.out.println("Sum of item and total = " + (Comput1.item +
Comput2.total));
newBarrier.reset();
System.out.println(" reset successful");
}
}
Explanation
While the other thread is processing a task, the value is summed up.
Output:
Example #3
Code:
import java.util.*;
import java.util.concurrent.*;
public class Async {
static List<Task> tasks = new ArrayList<>();
static ExecutorService executor = Executors.newScheduledThreadPool(3);
public static void main(String[] args) {
createTasks();
executeTasks();
}
private static void createTasks() {
for (int k= 0; k < 10; k++) {
tasks.add(new Task(k));
}
}
private static void executeTasks() {
for (Task task : tasks) {
executor.submit(task);
}
}
static class Task extends Thread {
int n;
public void run() {
try {
Thread.sleep(new Random (). nextInt (1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
printNum();
}
private void printNum() {
System.out.print(n + " ");
}
public Task(int n) {
this.n = n;
}
}
}
Explanation
The above code initiates a task by assigning a thread value, i.e., a worker thread. Here we stop the synchronous task in the print numb() function. Therefore, the output looks like this:
Output:
Example #4 – Time seconds
Async.html
<html>
<meta charset="utf-8"/>
<body> Understanding JavaScript Program Execution</br>
<script type="text/javascript">
function tensec()
{
return new Promise((resolve,reject)=>{ setTimeout(() => {
console.log('EDUCBA PAge -I take 20 second');
resolve();
}, 10000);
});
}
async function run()
{
console.log('EDUCBA PAge : Page executed immediately');
await tensec();
console.log('EDUCBA PAge : Next process');
}
run();
</script>
</body>
</html>
Explanation
The above code executes its promises and shows their wait time interval with the help of async-await. For example, the script above waits for 20 sec to complete the task.
Output:
Conclusion
Coming to an end, writing asynchronous code is a little harder, and most- importantly, promises are the general way to define the flow of delayed execution. In this article, we learned how to write asynchronous code that looks like synchronous. Using async has been more important in complex code. The JavaScript developer must understand much about this concept.
Recommended Articles
We hope this EDUCBA information on “Java async await” was beneficial to you. You can view EDUCBA’s recommended articles for more information.