Explain Async and EnableAsync annotation

Explain Async and EnableAsync annotation

The `@Async` and `@EnableAsync` annotations in Spring are used to facilitate asynchronous processing, allowing methods to run in the background without blocking the main thread. This is useful for performing tasks that can be executed independently, such as sending emails or processing long-running tasks.

  • `@Async`: This annotation is applied to a method to indicate that it should be executed asynchronously. When a method annotated with `@Async` is called, Spring executes it in a separate thread, allowing the caller to continue processing without waiting for the method to complete.
  • `@EnableAsync`: This annotation is used to enable the processing of asynchronous methods in Spring. It needs to be placed on a configuration class to activate Spring’s asynchronous method execution capability.

Async and EnableAsync annotation

Example Async and EnableAsync annotation

Step 1: Create a Spring Boot Application

Ensure you have the necessary dependencies in your `pom.xml` (for Maven) or `build.gradle` (for Gradle).

Example
Maven Dependency:
```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
```

Gradle Dependency:
```groovy
implementation 'org.springframework.boot:spring-boot-starter'
```

Step 2: Enable Asynchronous Processing

Create a configuration class to enable asynchronous processing.

Example
```java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
```

Explanation:

  • @EnableAsync: This annotation is added to the main application class or a configuration class to enable asynchronous method execution

Step 3: Create an Asynchronous Service

Define a service class with an asynchronous method.

Example
```java
package com.example.demo.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    @Async
    public void performAsyncTask() {
        try {
            Thread.sleep(5000); // Simulating a long-running task
            System.out.println("Asynchronous task completed.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
```

Explanation:

  • @Async: Applied to the performAsyncTask method, indicating that it should be executed asynchronously. The method will run in a separate thread, allowing the main thread to continue.

Step 4: Create a Controller to Trigger the Asynchronous Task

Create a REST controller to trigger the asynchronous service.

Example
```java
package com.example.demo.controller;

import com.example.demo.service.AsyncService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {

    private final AsyncService asyncService;

    public ApiController(AsyncService asyncService) {
        this.asyncService = asyncService;
    }

    @GetMapping("/run-task")
    public String runTask() {
        asyncService.performAsyncTask();
        return "Asynchronous task started.";
    }
}
```

Explanation:

  • @RestController: Indicates that this class is a REST controller.
  • @RequestMapping("/api"): Maps the URL /api to the ApiController methods.
  • @GetMapping("/run-task"): Maps HTTP GET requests to the runTask method, which triggers the asynchronous task.

Step 5: Running the Application

Run the application from the main class (DemoApplication). Access the /api/run-task endpoint to start the asynchronous task.

Step 6: Observing the Asynchronous Behavior

Monitor the console logs:

  • When you access /api/run-task, you will see “Asynchronous task started.” immediately.
  • After 5 seconds, “Asynchronous task completed.” will appear in the console, indicating that the asynchronous task has completed.

Conclusion of Async and EnableAsync annotation

  • @Async: Marks a method to be executed asynchronously in a separate thread.
  • @EnableAsync: Enables Spring’s support for asynchronous method execution.
  • Example: Demonstrated how to use @Async and @EnableAsync to perform background tasks in a Spring Boot application.

Homepage

Readmore