I'm new to asynchronous task execution in Spring, so please forgive me if this sounds like a silly question.
I read that @Async annotation is introduced from Spring 3.x onward at method level to invocation of that method will occur asynchronously. I also read that we can configure the ThreadPoolTaskExecutor in the spring config file.
What I'm not able to understand is that how to call a @Async annotated method from a tak executor lets suppose - AsyncTaskExecutor
Earlier we used to do something like in a class:
@Autowired protected AsyncTaskExecutor executor;
And then
executor.submit(<Some Runnable or Callable task>)
I'm not able to understand the relationship between @Async annotated methods and TaskExecutor.
I tried searching a lot over the internet but could not get anything on this.
Can somebody provide an example for the same.
Complete Example
Config Spring
Executor Class Created, Executor i have created so that spring takes care of thread management.
Create a manager.
Configure your service class.
Model.
Test to Run
Here's an example of
@Async
use:Now call that method from another class and it will run asynchronously. If you want a return value use a
Future
The relationship between
@Async
andTaskExecutor
is that@Async
uses aTaskExecutor
behind the scenes. From the docs:So to set up a default executor, add this to your spring config
Or to use a particular executor for a single use try
See http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async
You can add @Async on your method and the following to your Application context.
In the config file, one should mention an annotation driven task with the thread pool name and method with @Async(pool name) will be executed as part of that pool. This creates a proxy class for the one which has @Async annotation and executes it for every thread.