Spring
Top 10 questions related to Async processing in Spring
Questions and answers on asynchronous methods, executors, scheduling, and error handling in Spring.
-
How do you enable asynchronous processing in Spring?
Use@EnableAsyncon a configuration class to enable async support. -
How do you define an asynchronous method in Spring?
Annotate the method with@Asyncand ensure it returnsvoid,Future,CompletableFuture, orListenableFuture. -
How do you configure a thread pool for async tasks in Spring?
Define aThreadPoolTaskExecutorbean and customize its properties like pool size. -
What happens if an async method throws an exception?
Exceptions are caught by the async executor; useAsyncUncaughtExceptionHandlerto handle them. -
How do you schedule a recurring task in Spring?
Use@Scheduledwith attributes likefixedRate,fixedDelay, orcronfor scheduling. -
What is the difference between
@Asyncand@Scheduled?
@Asyncruns methods asynchronously on demand, while@Scheduledruns tasks on a fixed schedule. -
How do you ensure a scheduled task runs only once across a cluster?
Use a distributed lock or a task scheduler like Quartz with database persistence. -
Can you call an
@Asyncmethod from the same class?
No, it requires a proxy; call it from another bean or useApplicationContextto get the bean. -
How do you monitor the status of async tasks in Spring?
UseCompletableFutureorListenableFutureto track task completion or add custom logging. -
What is the default executor for
@Asyncin Spring?
Spring uses aSimpleAsyncTaskExecutor, creating a new thread per task unless customized.