Play SpringBoot's timing task @Scheduled thread pool configuration

Read the text:

Friends who are interested in knowing the content and more related learning materials, please like and collect + comment and forward + follow me, there will be a lot of dry goods later. I have some interview questions, architecture, and design materials that can be said to be necessary for programmer interviews!
All the materials are organized into the network disk, welcome to download if necessary! Private message me to reply [111] to get it for free

preamble

For timing tasks, only need to use the @Scheduled annotation in SpringBoot to meet the requirements. Its appearance also brings us great convenience. We only need to add this annotation and set it according to the requirements to use the timing task. .

However, we need to note that @Scheduled 并不一定会按时执行.

Because although the timing tasks using @Scheduled are executed asynchronously , different timing tasks are not parallel ! ! ! ! ! ! ! !

Before one of the scheduled tasks is executed, other scheduled tasks will not be executed even if it is time to execute, and they will be queued.

That is, if you want your different scheduled tasks to not affect each other and will be executed when the time comes, then you'd better make your scheduled task method an asynchronous method, so that the scheduled task is actually equivalent to calling a thread to execute the task , it was over in an instant. For example use:@Async

Of course, you can also force your scheduled tasks to be executed regularly. However, as a qualified programmer

So, how to make the timing task implemented by @Scheduled asynchronous? At this point you need to configure the thread pool for @Scheduled.

Configuration example

package com.java.navtool.business.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author :mmzsblog.cn
 * @date :Created in 2021/7/27 17:46
 * @description:spring-boot 多线程  @Scheduled注解 并发定时任务的解决方案
 * @modified By:
 * @version:
 */

@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    public static final String EXECUTOR_SERVICE = "scheduledExecutor";

    @Bean(EXECUTOR_SERVICE)
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        // 设置最大线程数
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 10);
        // 设置队列容量
        executor.setQueueCapacity(Runtime.getRuntime().availableProcessors() * 10);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(10);
        // 设置默认线程名称
        executor.setThreadNamePrefix("scheduled-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

}

Incidentally introduce several parameters of the thread pool. You need to understand thoroughly, don't memorize it by rote!

Thread pool parameters

  • 1. corePoolSize (required): the number of core threads.
  • 2. maximumPoolSize (required): the maximum number of threads.
  • 3. keepAliveTime (required): The idle time of the thread. If this time is exceeded, non-core threads will be recycled.
  • 4. unit (required): specify the time unit of keepAliveTime. Commonly used are: TimeUnit.MILLISECONDS (milliseconds), TimeUnit.SECONDS (seconds), TimeUnit.MINUTES (minutes).
  • 5. workQueue (required): task queue. Runnable objects submitted through the execute() method of the thread pool will be stored in this queue.
  • 6. threadFactory (optional): thread factory. Generally use the default.
  • 7. handler (optional): rejection policy. When the number of threads reaches the maximum number of threads, the saturation strategy will be executed.

Talk about the difference between the number of core threads and the maximum number of threads:

Deny policy optional values:

  • 1. AbortPolicy (default): Abort the task and throw a RejectedExecutionException.
  • 2. CallerRunsPolicy: The task is handled by the calling thread.
  • 3. DiscardPolicy: Give up the task, but do not throw an exception. This mode can be used for custom processing.
  • 4. DiscardOldestPolicy: Abandon the oldest unprocessed task in the queue, and then try to execute the task again.

Thread pool execution process:

For the previous flow chart, try to see if you can understand it yourself:

A brief summary of the thread pool execution process:

  • 1. After a task is submitted to the thread pool, if the current number of threads does not reach the number of core threads, create a new thread and execute the new task. Note that the thread will not be destroyed after the new task is executed;
  • 2. If it is reached, then judge whether the task queue is full, if not, put the task into the task queue;
  • 3. If it is full, judge whether the current number of threads has reached the maximum number of threads. If not, create a new thread to execute the task. Note that if the number of threads in the thread pool is greater than the number of core threads, whenever a thread exceeds the idle time , it will be destroyed until the number of threads is not greater than the number of core threads;
  • 4. If the maximum number of threads is reached and the task queue is full, the saturation strategy will be executed;

 

Guess you like

Origin blog.csdn.net/m0_69424697/article/details/125152697