Session JDBC Effect on Scheduling Thread Pool

Published by Bilal Kaun on

When @EnabledScheduling annotation is visible in the context, Spring Boot’s Autoconfigurers usually create two Thread Pools

  • ThreadPoolTaskExecutor
  • ThreadPoolTaskScheduler

As their names imply, the Task Executor is used for executing tasks, while the Task Scheduler is used to run scheduled tasks – such as those annotated with @Scheduled. The size of this scheduled-pool is specified using the ‘spring.task.scheduling.pool.size’ property – set to ‘1’ by default. The scheduled pool is autoconfigured on condition that no other relevant configuration already exist, and at the time of this writing, these include the following Beans types:

  • SchedulingConfigurer
  • TaskScheduler
  • ScheduledExecutorService

Should any Bean already exist with one of these types, Scheduled task pool will not be created. Without a scheduled pool, Scheduled tasks run sequentially. This is problematic for scenarios where you may expect multiple methods annotated with the @Scheduled to run concurrently (so you’ve specified a higher value than one for the property ‘spring.task.scheduling.pool.size’). It may also affect timing of the scheduled tasks should a run take longer than expected.

This is where the Session JDBC (spring-session-jdbc) project causes issues. It contains a clean-up task which has the responsibility of removing expired sessions from the session table in the database. By default, it runs every minute and requires the Scheduling pool. Unfortunately the clean-up task is scheduled using the SchedulingConfigurer class – one of the conditional-missing-beans required for autoconfigurer to instantiate ThreadPoolTaskScheduler. This means no scheduled thread pool and your integration tests begin to fail.

The solution can be complex or simple given the structure of your project and what dependencies you’re using. For relatively straight forward Spring Boot projects, manually configuring the ThreadPoolTaskScheduler bean does the trick.

In a @Configuration class, simply copy the code from the autoconfigurer (so it loads all the correct arguments from the properties file).

@Bean
public ThreadPoolTaskScheduler taskScheduler(TaskSchedulerBuilder builder) {
    return builder.build();
}

That’s it.


0 Comments

Leave a Reply