I have two Async methods that are configured to use the same TaskExecutor.
@Async("myExecutor")
public void foo() {
system.out.println("foo from: " + Thread.currentThread().getName());
}
@Async // this should use the primary defaultExecutor
// try to bombard the single thread pool with bunch of requests
public void generateFoo() {
while(true) {
system.out.println("generateBar from: " + Thread.currentThread().getName());
this.foo();
}
}
I want the underlining threadpool of myExecutor to have a coresize and maxsize of 1 and queue incoming requests for the thread. I.e only one thread executing foo() runs at a time and all other calls to foo() waits for their turn. In my Spring configuration class, I have
@Configuration
@ComponentScan(basePackages = { "com.test" })
@EnableAsync
@EnableScheduling
public class FooBarConfig {
@Bean
@Primary
@Qualifier("defaultExecutor")
public TaskExecutor defaultExecutor() {
return new ThreadPoolTaskExecutor();
}
@Bean
@Qualifier("myExecutor")
public TaskExecutor myExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.setQueueCapacity(Integer.MAX_VALUE);
return executor;
}
}
However, I'm seeing that foo() isn't always being executed from the same thread. If I call foo() via a @Scheduled task from another thread, it runs on "myExecutor-1" as expected. But if foo() is called via generateFoo(), it seems to be running in whatever generateFoo() runs from, ie:
foo from: defaultExecutor-1
foo from: myExecutor-1
foo from: defaultExecutor-1
foo from: defaultExecutor-1
foo from: defaultExecutor-1
If I get rid of generateFoo()'s @Async, foo() still runs on whatever thread generateFoo() is running on.
Am I using the wrong TaskExecutor for what I'm looking for or configuring it incorrectly?
edit As state in my original post, not making generateFoo() an async method doesn't seem to do the trick, as someone suggested.