Reputation: 8353
I am using Spring Boot 1.5.x, and in details, I am using the @Async
annotation. My problem is that I have the following method in a repository.
@Repository
class Repository {
@Async
CompletableFuture<String> findSomething() {
/* Some code that returns something */
}
}
And then, I have the following method in a service, which calls the above repository.
@Service
class Service {
private Repository repository;
// ...
@Async
CompletableFuture<String> findSomething() {
return repository.findSomething()
}
}
My question is: should I place the @Async
annotation also in the service.findSomething()
method? Or should I place the annotation only in the service method?
I mean, Spring should schedule the execution of a method marked with @Async
annotation in a dedicated thread. Is it correct?
Thanks in advance.
Upvotes: 2
Views: 1407
Reputation: 1015
Annotating a method with @Async
will cause the caller to return immediately and the actual execution will occur in a separate thread as part of a task submitted to the default SimpleAsyncTaskExecutor
(if you haven't configured another one). Please see the relevant spring documentation.
That being said, for your goal there's no added benefit in nesting the @Async
. If your goal is to make Repository.findSomething
asynchronous and to be able to call it from different places, not only Service.findSomething
, you should annotate only this method.
Also, Service.findSomething
is asynchronous itself, even if not annotated with @Async
, in the scenario you depicted. The method is not blocking by calling CompletableFuture.get()
and it will return immediately, although it will not be executed in a separate thread.
Upvotes: 1