Sobes.tech
Junior — Middle

What is the role of the Async annotation in Spring and how does it affect method execution?

sobes.tech AI

Answer from AI

The @Async annotation in Spring is used to designate methods that should be executed asynchronously, meaning in a separate thread, without blocking the main execution thread.

When a method is marked with @Async, Spring creates a separate thread for it from a thread pool and executes the method in parallel with the rest of the application. This is useful for performing long-running or resource-intensive operations, such as sending emails, processing files, or calling external services, without delaying the main thread.

Example:

@Service
public class EmailService {

    @Async
    public void sendEmail(String recipient) {
        // long operation to send email
    }
}

Important:

  • To enable @Async support, you need to activate asynchronous processing, for example, by using @EnableAsync in your configuration.
  • Methods should be public and called from another bean so that Spring's proxy can intercept the call.

Thus, @Async helps improve application responsiveness by allowing tasks to run in parallel.

What is the role of the Async annotation in Spring… - sobes.tech