Member-only story

@Async — Spring Asynchronous Processing

theoneamin
3 min readAug 1, 2022

--

In a normal program, the code gets run from the top to the bottom. You can have a line of code that calls a method at the bottom of the file and when the method processing is done, the code execution returns to where the method was called from and continues running code underneath.

Sometimes, these methods can take longer to complete execution and for this, we can make these kinds of methods asynchronous so that code continues to execute without having to wait for the method to complete.

Spring’s @Async annotation is used to introduce asynchronous execution. Whenever the executor comes across a method annotated as async, it will process it in a different thread the rest of the code execution continues.

For async to work, you’ll need to make sure your methods are not in the same class that calls them ie you can’t call an async method from within the same class.

Enabling Async

To enable async annotation, we need to add the @EnableAsync to our main class.

Example using Async

Let’s assume we have a service class that processes customer orders. Whenever a customer places an order, we want to perform a series of logic one of them being notifying the customer. We can notify the customer that their order has…

--

--

theoneamin
theoneamin

No responses yet