I configured a ThreadPoolTaskExecutor
, but the outcome is different than I expected. It the following behaviour correct? And how could it be explained?
@Bean
public TaskExecutor taskExecutor() {
int core = 1;
int max = 1;
int queue = 2;
ThreadPoolTaskExecutor bean = new ThreadPoolTaskExecutor();
bean.setCorePoolSize(core);
bean.setMaxPoolSize(max);
bean.setQueueCapacity(queue);
bean.setKeepAliveSeconds(60);
return bean;
}
@Scheduled(initialDelay = 5000, fixedDelay = 10000)
public void init() {
int nthreads = 1;
for (int i = 0; i < nthreads; i++)
async.run(i);
}
@Service
public class MyAsync {
@Async("taskExecutor")
public void run(int i) {
Sysout("running: " + i);
}
}
Who can explain the following result for different pool configurations:
- core = 1, max = 1, queue = 2: RejectedExecutionException thrown (why, because I just created 1 thread?)
- core = 1, max = 2, queue = 2: RejectedExecutionException thrown (again: why? two threads should be allowed, and I'm just starting
nthreads=1
.) - core = 1, max = 2, queue = 5: nothing happens. No sysout is printed (why?)
- core = 1, max = 2, queue = 5, nthreads = 3: nothing happens
- core = 1, max = 2, queue = 5, nthreads = 4: now this one executes, but starts throwing RejectedExecutionException
- core = 2, max = 2, queue = 5, nthreads = 4: again, nothing happens
I don't get this behaviour of the async executor.
My goal is as follows: create an Executor
that has 1-2 threads running (depending on the load). Tasks should be queued up to 5 threads. And if any thread is in the queue for more than 60 seconds, they should time out and be removed if not executed.