Performance: @EnableAsync annotation
This annotation affects how tasks run asynchronously, improving responsiveness by offloading work from the main thread.
@Service public class MyService { @Async public void longTask() { // long running code } } // @EnableAsync must be added to a @Configuration class (e.g., your @SpringBootApplication main class)
@Service
public class MyService {
public void longTask() {
// long running code
}
}| Pattern | Thread Usage | Main Thread Blocking | Responsiveness Impact | Verdict |
|---|---|---|---|---|
| Synchronous method | Single main thread | Blocks main thread | High input delay | [X] Bad |
| @Async method with @EnableAsync | Separate worker thread | No main thread block | Improved input responsiveness | [OK] Good |
@EnableAsync annotation in a Spring Boot application?@EnableAsync does@EnableAsync.@EnableAsync = run methods asynchronously [OK]@EnableAsync must be on a configuration or main class to activate async support globally.@Async@Async annotation.@EnableAsync on a configuration class and @Async on methods -> Option D@EnableAsync on a configuration class and @Async on methods [OK]mainMethod() is called?@EnableAsync
@Configuration
public class AppConfig {}
@Service
public class MyService {
@Async
public void asyncMethod() {
System.out.println("Async task started");
}
public void mainMethod() {
System.out.println("Main method start");
asyncMethod();
System.out.println("Main method end");
}
}@Async method runs asynchronously only when called from a different Spring-managed bean proxy. Calling asyncMethod() directly within the same class does NOT run asynchronously, so it executes synchronously.@Configuration
public class AsyncConfig {
@Async
public void runAsync() {
System.out.println("Running async");
}
}@EnableAsync on a configuration or main class, Spring will not run @Async methods asynchronously.@Async methods can be void, can be in any Spring bean, and do not need to be static.@EnableAsync annotation to activate async support -> Option A@EnableAsync and @Async to achieve this?@Configuration
@EnableAsync
public class AsyncConfig {}
@Service
public class TaskService {
@Async
public CompletableFuture<String> slowTask(String name) {
Thread.sleep(2000);
return CompletableFuture.completedFuture(name + " done");
}
}
// In some controller or service
public void runTasks() {
CompletableFuture<String> t1 = taskService.slowTask("Task1");
CompletableFuture<String> t2 = taskService.slowTask("Task2");
CompletableFuture.allOf(t1, t2).join();
System.out.println("All tasks completed");
}@EnableAsync is present to enable async support, and @Async marks slowTask to run asynchronously returning CompletableFuture.CompletableFuture.allOf(...).join() waits for both to finish without blocking main thread execution during tasks.Pass the test and this pattern moves unknown