Reputation: 285
I want to understand the difference between the two codes I am using Java and Springboot. Are they both equivalent -
a. Without using @Async and spawning a new thread/task an submitting to the taskexecutor b. One that uses @Async along with the executor name
a.
public void executeNewThread() {
Thread t = new Thread( ()->{
try {
Thread.sleep(10000);
//we are using nasa open API
fetchNasaLocInfo();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
taskExecutor.execute(t);
}
b.
@Async("specificTaskExecutor")
public void executeAsync() {
try {
Thread.sleep(10000);
//we are using nasa open API
fetchNasaLocInfo();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Upvotes: 2
Views: 1324
Reputation: 44368
These two links directly from Spring probably provide a sufficient answer to your question.
@Async
Basically, the annotated method with @Async
is considered as an asynchronous method and should return either Future
or its specification or void
. The method runs in a thread taken from a specified executor service's thread pool (@Async("specificTaskExecutor")
), which is usually provided as a bean:
@Bean(name = "specificTaskExecutor")
public TaskExecutor specificTaskExecutor() {
ThreadPoolTaskExecutor specificTaskExecutor = new ThreadPoolTaskExecutor();
specificTaskExecutor.initialize();
return specificTaskExecutor;
}
Upvotes: 1