The @Async annotation

Once asynchronous processing is enabled, then the methods that are annotated with the @Async annotation will execute asynchronously.

The following is a simple example of the @Async annotation:

public class AsyncTask {
private static final Logger LOGGER =
Logger.getLogger(AsyncTask.class);
@Async
public void doAsyncTask() {
try {
LOGGER.info("Running Async task thread : " +
Thread.currentThread().getName());
} catch (Exception e) {
}
}
}

We can also annotate the @Async annotation to a method with the return type, as follows:

@Async
public Future<String> doAsyncTaskWithReturnType() {
try
{
return new AsyncResult<String>("Running Async task thread : " +
Thread.currentThread().getName());
}
catch (Exception e) {
}
return null;
}

In the previous code, we used the AsyncResult class, which implements Future. This can be used to get the results of the execution of the asynchronous method.

The following is the code to call the asynchronous method from the main method:

public class asyncExample {
private static final Logger LOGGER =
Logger.getLogger(asyncExample.class);
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext ctx = new
AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
AsyncTask task = ctx.getBean(AsyncTask.class);
LOGGER.info("calling async method from thread : " +
Thread.currentThread().getName());
task.doAsyncTask();
LOGGER.info("Continue doing something else. ");
Thread.sleep(1000);
}
}

When we compile and run the preceding class, we will get the following output:

calling async method from thread : main
Continue doing something else.
Running Async Task thread : SimpleAsyncTaskExecutor-1
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset