Running tasks asynchronously using @Async

You can also trigger tasks asynchronously using the @Async annotation. Consider the following example:

@Component
public class AsyncTask {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Async
void doThisAsynchronously() {
IntStream.range(1, 100).forEach(x - > logger.info("AsyncTask {}", x));
}

}

When doThisAsynchronously is called on the bean, it will always be executed asynchronously.

Before using @Async, we need to ensure that @EnableAsync is added to our Spring Boot application class:

@EnableAsync
public class TaskSchedulingApplication implements CommandLineRunner {

Consider the following code to trigger doThisAsynchronously:

@Autowired
private AsyncTask asyncTask;
@Override
public void run(String...args) throws Exception {
asyncTask.doThisAsynchronously();
IntStream.range(1, 100).forEach(x - > logger.info("TaskSchedulingApplication {}", x));
}

We are autowiring AsyncTask in and implementing the run method of CommandLineRunner to trigger doThisAsynchronously, in parallel with other code.

You can see that the code runs asynchronously. You can also see that there are logs related to TaskSchedulingApplication before AsyncTask completes execution:

[ task-1] c.m.spring.taskscheduling.AsyncTask : AsyncTask 86
[ task-1] c.m.spring.taskscheduling.AsyncTask : AsyncTask 87
[ main] plication$$EnhancerBySpringCGLIB$$3ed9f7 : TaskSchedulingApplication 1
[ task-1] c.m.spring.taskscheduling.AsyncTask : AsyncTask 88
//More log
//More log
[ main] plication$$EnhancerBySpringCGLIB$$3ed9f7 : TaskSchedulingApplication 2
..................Content has been hidden....................

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