Junior — Middle
How can you configure background task execution in Spring so that they do not block the main thread?
sobes.tech AI
Answer from AI
In Spring, the @Async annotation is used to execute tasks in the background. It allows methods to run asynchronously without blocking the main thread.
To make this work, you need:
- Enable asynchronous support in the configuration by adding
@EnableAsyncto the configuration class. - Annotate the method that should run in the background with
@Async.
Example:
@Configuration
@EnableAsync
public class AsyncConfig {
}
@Service
public class MyService {
@Async
public void doBackgroundTask() {
// Long operation
System.out.println("Running in the background");
}
}
When calling doBackgroundTask() from another bean, the method will run in a separate thread, not blocking the caller.
Important: The call to the asynchronous method must occur through the Spring container (e.g., via dependency injection), otherwise @Async will not work.