41

I'm trying to use Async annotation in Spring but I'm getting

java.lang.IllegalStateException: ThreadPoolTaskScheduler not initialized

error, when I try to run the method marked as Async. The following is the configuration for Async:

@EnableScheduling
@EnableAsync
@Configuration 
public class SchedulingConfiguration implements AsyncConfigurer{

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        return scheduler;
    }

}

and the following is the declaration of async method.

@Async
@Transactional(value = "baseTransactionManager", isolation = Isolation.READ_COMMITTED)
public void foo(Bar bar) {// some code here}

What am I missing in here?

Thanks in advance.

1 Answer 1

76

You have to explicitly call scheduler.initialize() after setting all properties but before returning the scheduler.

See full working test case here.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, the exception does not occur but the method with async does not perform either. Are there anything else that I should do?
@small_ticket What exactly do you mean by 'does not perform'? The foo() method - is it inside properly configured Spring bean, eg. FooService? Do you call it from other bean where FooService is autowired, or from the same bean?
foo is in a Service FooService and I'm calling it from another Service CallerService where FooService is autowired. The code in the foo does not execute, this is what i mean. It doesn't print the logs, it doesn't insert the necessary data into the database, etc.
Stavnichy I found the reason why my async method is not working. I have to specify componentScan in my Configuration class. My configuration class is imported in the main configuration and I have the component scan in my parent configuration file. However, it is not enough for Async, therefore I've added componentScan to the AyncConfiguration file and everything works just fine. Thanks a lot!
Note that calling initialize() is necessary only if your scheduler is not a Spring bean, otherwise it is called automatically in afterPropertiesSet().
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.