CodeGym /Java Course /Module 5. Spring /Planning and execution of tasks

Planning and execution of tasks

Module 5. Spring
Level 15 , Lesson 9
Available

If there is no Executor bean in the context, Spring Boot automatically configures the ThreadPoolTaskExecutor with adequate default values that can be automatically associated with asynchronous task execution (the @EnableAsync annotation) and asynchronous request processing in Spring MVC.

If you define a custom Executor in the context, during normal task execution (that is, with the @EnableAsync annotation) it will be used transparently, but Spring MVC support will not be configured because it requires an AsyncTaskExecutor implementation (named applicationTaskExecutor). Depending on your target organization, you can change Executor to ThreadPoolTaskExecutor, or define both ThreadPoolTaskExecutor and AsyncConfigurer wrapping your custom Executor.

Autoconfiguration TaskExecutorBuilder allows you to easily create instances that replicate what autoconfiguration does by default.

The thread pool uses 8 main threads, the number of which can increase and decrease depending on the load. These default settings can be fine-tuned using the spring.task.execution namespace, as shown in the following example:

Properties
spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s
Yaml
spring:
  task:
    execution:
      pool:
        max-size: 16
        queue-capacity: 100
        keep-alive: "10s"

This code modifies the thread pool to use a queue with a length limit, so that if the queue becomes full (100 tasks), the thread pool is increased to a maximum of 16 threads. Pool pruning is more aggressive because threads are restored if they are idle for 10 seconds (rather than the default 60 seconds).

The Scheduler ThreadPoolTaskScheduler can also be automatically configured if it needs to be associated with the execution of scheduled tasks (for example, using the @EnableScheduling annotation). The default thread pool uses a single thread, but its settings can be fine-tuned using the spring.task.scheduling namespace, as shown in the following example:

Properties
spring.task.scheduling.thread-name-prefix=scheduling-
spring.task.scheduling.pool.size=2
Yaml
spring:
  task:
    scheduling:
      thread-name-prefix: "scheduling-"
      pool:
        size: 2

The TaskExecutorBuilder and TaskSchedulerBuilder beans are available in the context if you need to create a custom executor or scheduler.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION