Table of Contents
1: ThreadPoolTaskExecuto
Home Java javaTutorial How to implement Springboot's own thread pool

How to implement Springboot's own thread pool

Jun 28, 2023 pm 04:33 PM
Thread Pool

1: ThreadPoolTaskExecuto

1 ThreadPoolTaskExecutor thread pool:

ThreadPoolTaskExecutor is Spring’s secondary encapsulation based on Java’s own thread pool ThreadPoolExecutor. The main purpose is to make it more convenient in the spring framework system The thread pool is used in Spring, which is the default thread pool in Spring

2 Use ThreadPoolTaskExecutor to inject beans into ioc
Configuration file form, Spring will automatically configure

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

## 默认线程池配置,ThreadPoolTaskExecutor

# 核心线程数

spring.task.execution.pool.core-size=8 

# 最大线程数

spring.task.execution.pool.max-size=16

# 空闲线程存活时间

spring.task.execution.pool.keep-alive=60s

# 是否允许核心线程超时

spring.task.execution.pool.allow-core-thread-timeout=true

# 线程队列数量

spring.task.execution.pool.queue-capacity=100

# 线程关闭等待

spring.task.execution.shutdown.await-termination=false

spring.task.execution.shutdown.await-termination-period=

# 线程名称前缀

spring.task.execution.thread-name-prefix=demo_Thread

Copy after login

Configuration form:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.ConcurrentMap;

import java.util.concurrent.Executor;

import java.util.concurrent.ScheduledFuture;

//@Configuration

public class ThreadConfig {

    @Value("${task.maxPoolSize}")

    private int maxPoolSize;

    //todo 其他的相关配置都可以通过配置文件中注入

    @Bean("ThreadPoolTaskExecutor")

    public Executor myAsync() {

        final ThreadPoolTaskExecutor executor =

                new ThreadPoolTaskExecutor();

        executor.setMaxPoolSize(maxPoolSize);

        //todo  其他参数设置

        //初始化

        executor.initialize();

        return executor;

    }

}

Copy after login

3 After creating threads, all thread pools are obtained from ioc

4 Thread pool processing process:

(1) Check whether the core thread pool is full. If not, create a thread for execution Task, if the number of core threads is full, check whether the task queue is full. If not, store the thread in the task queue. If the task queue is full, check the maximum number of threads. If not, create a thread to execute the task. If it is full, execute according to the rejection policy

(2) Deny policy:

  • ##CallerRunsPolicy(): The original thread executes

  • AbortPolicy(): Throws an exception directly

  • DiscardPolicy(): Discard directly

  • DiscardOldestPolicy(): Discard the oldest item in the queue

Two: ThreadPoolTaskScheduler

1 ThreadPoolTaskScheduler regularly schedules task thread pools and processes asynchronous tasks

2 Usage: Inject the bean of ThreadPoolTaskScheduler

(1) Configuration file format: ..

(2) Configuration class form:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.ConcurrentMap;

import java.util.concurrent.ScheduledFuture;

@Configuration

public class ThreadPoolTaskSchedulerConfig {

    @Bean

    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {

        final ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        //设置等待任务在关机时l候完成

        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);

        //设置等待时间为60s

        threadPoolTaskScheduler.setAwaitTerminationSeconds(60);

        return threadPoolTaskScheduler;

    }

}

Copy after login

3 Use ThreadPoolTaskScheduler scheduled task

Use for ordinary thread pool:

  • submit( callable), the execution result is required

  • submit(runnable), the execution result is not required

(1) Scheduled task

Add the task content Runnable, set the execution period Trigger/Date, and the Trigger expression can be Baidu

1

2

schedule(Runnable task,Trigger)

schedule(Runnable task,Date)

Copy after login

(2) Specify the interval to execute a task. The time interval is from the completion of the previous task to the start of the next task, in milliseconds

1

scheduleWithFixedDelay(Runnable task,long delay)

Copy after login

(3) Execute tasks at a fixed frequency and execute new tasks at intervals after the task starts. If the last task is completed, wait for the last task to be completed before executing the next task

1

scheduleAtFixedRate(Runnable task,long delay)

Copy after login

(4) Scheduled task cancellation:

Set the collection where the scheduled task is stored. The result of the scheduled task execution is ScheduledFuture. Store the object in the collection and obtain the ScheduledFuture< in the collection. ?>Object.cancel(true) cancels the scheduled task

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import org.springframework.scheduling.support.CronTrigger;

import org.springframework.stereotype.Service;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.concurrent.*;

@Service

public class SchedulerService {

    @Autowired

    ThreadPoolTaskScheduler scheduler;

    /**

     * 常规线程池使用

     */

    public void tesScheduler1() throws ExecutionException, InterruptedException {

        //无返回值

        final Future<?> demo_scheduler1 = scheduler.submit(new Runnable() {

            @Override

            public void run() {

                System.out.println("demo runnable scheduler");

            }

        });

        //无返回值

        final Future<?> demo_scheduler2 = scheduler.submit(new Callable<Object>() {

            @Override

            public Object call() throws Exception {

                System.out.println("demo callable  scheduler");

                return "callable";

            }

        });

        System.out.println("result:" + demo_scheduler2.get());

    }

    /**

     * 定时任务

     */

    public void tesScheduler2() throws ParseException {

        //CronTrigger表达式百度即可

        scheduler.schedule(() -> {

            System.out.println("定时任务");

        }, new CronTrigger("0/1****?"));

        //创建指定时间的日期

        final Date date = new Date(2023, 3, 26, 21, 35);

        final DateFormat format = new SimpleDateFormat();

        final Date parse = format.parse("2023-03-26-21-26");

        scheduler.schedule(() -> {

            System.out.println(new Date());

        }, parse);

    }

    /**

     * 指定时间间隔执行任务,上次任务结束到下次任务开始的时间间隔

     */

    public void tesScheduler3() {

        scheduler.scheduleWithFixedDelay(() -> {

            //todo

        }, 300L);

    }

    /**

     * 固定频率执行任务,在固定一段时间后便会执行下次任务,

     * 如果时间到了上次任务还没执行完毕则等待,

     * 直到上一次任务执行完毕后立马执行下次任务

     */

    public void tesScheduler4() {

        scheduler.scheduleAtFixedRate(new FutureTask<String>(new Callable<String>() {

                    @Override

                    public String call() throws Exception {

                        return null;

                    }

                }),

                200);

    }

    //取消定时任务队列

    public static ConcurrentMap<String, ScheduledFuture> map = new ConcurrentHashMap<>();

    public void startTask(String k1) {

        map.compute(k1, (k, v) -> {

            if (map.containsKey(k)) return v;

            map.put(k, v);

            return v;

        });

    }

}

Copy after login

Three @Scheduled implements the scheduled task, annotation enables the scheduled task

1 Use @EnableScheduled to enable support

2 @ Scheduled annotation method

(1)@Scheduled(fixedDelay=5000) delayed execution, executed after 5s

(2)@Scheduled(fixedRate=5000) scheduled execution, executed every five seconds
(3)@Scheduled(corn="002**?") Custom execution, corn expression Baidu, this execution method is commonly used, corn="002**?" starts executing scheduled tasks at two o'clock in the morning every day

3 Note that the tasks started by @Scheduled are single-threaded and easy to block

(1) Inject ThreadPoolTaskScheduler into ioc, then Scheduled will use the ThreadPoolTaskScheduler thread pool, which can solve the single-thread blocking problem

( 2) @Scheduled and @Async annotations enable scheduled tasks and specify the thread pool in @Async("pool"). If the thread pool is not specified, Spring's SimpleAsyncTaskExecutor thread pool will be used. This thread pool will add a thread to execute the task each time. , low efficiency

Four: Asynchronous tasks in Spring

1 @EnableAsync turns on asynchronous support

2 @Async turns on asynchronous tasks and specifies the thread pool

Note:@ Scheduled and @Async annotations enable scheduled tasks and specify the thread pool in @Async("pool"). If the thread pool is not specified, Spring's SimpleAsyncTaskExecutor thread pool will be used. This thread pool will add a thread to execute the task each time, which is inefficient. However, when @Async starts an asynchronous task alone, the default thread pool is used. It is recommended to customize the thread pool according to the needs.

Note: The return value of @Async can only be void or Future, and the caller and @Async cannot In a class, otherwise aop will not be used;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Service;

@Service

public class AsyncService {

    @Async

    public void showThreadName1() {

        //默认线程池

        System.out.println(Thread.currentThread().getName());

    }

    @Async("myPool")//指定线程池

    public void showThreadName2() {

        System.out.println(Thread.currentThread().getName());

    }

}

Copy after login

Five: Present a custom java thread pool:

1

2

3

4

5

6

7

8

9

10

@Bean("myPool")

   public Executor executor(){

      return new ThreadPoolExecutor(// 自定义一个线程池

               1, // coreSize

               2, // maxSize

               60, // 60s

               TimeUnit.SECONDS, new ArrayBlockingQueue<>(3) // 有界队列,容量是3个

               , Executors.defaultThreadFactory()

               , new ThreadPoolExecutor.AbortPolicy());

   }

Copy after login
java's own thread pool, cache, fixed number, single Threaded, timed,,,, six or seven types, continued

The above is the detailed content of How to implement Springboot's own thread pool. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python obtains tourist attraction information and reviews and creates word clouds and data visualization Python obtains tourist attraction information and reviews and creates word clouds and data visualization Apr 11, 2023 pm 08:49 PM

Hello everyone, I am Mr. Zhanshu! As the saying goes: Wouldn’t it be great to have friends from far away? It is a very happy thing to have friends come to play with us, so we must do our best to be landlords and take our friends to play! So the question is, when is the best time and where to go, and where is the most fun place? Today I will teach you step by step how to use the thread pool to crawl the attraction information and review data of the same trip and make word cloud and data visualization! ! ! Let you know information about tourist attractions in various cities. Before we start crawling data, let's first understand threads. Thread process: A process is a running activity of code on a data collection. It is the basic unit of resource allocation and scheduling in the system. Thread: It is a lightweight process, the smallest unit of program execution, and an execution path of the process. one

Common server load problems and their solutions under Linux systems Common server load problems and their solutions under Linux systems Jun 18, 2023 am 09:22 AM

Linux is an excellent operating system that is widely used in server systems. In the process of using Linux systems, server load problems are a common phenomenon. Server load means that the server's system resources cannot satisfy current requests, causing the system load to be too high, thus affecting server performance. This article will introduce common server load problems and their solutions under Linux systems. 1. The CPU load is too high. When the server's CPU load is too high, it will cause problems such as slower system response and longer request processing time. When C

How to use thread pool to implement circular scheduling of tasks in Java 7 How to use thread pool to implement circular scheduling of tasks in Java 7 Jul 29, 2023 pm 10:37 PM

How to use thread pools to implement circular scheduling of tasks in Java7 Introduction: When developing Java applications, using thread pools can improve task execution efficiency and resource utilization. In Java7, the thread pool can be used to easily implement circular scheduling of tasks. This article will introduce how to use thread pools to implement circular scheduling of tasks in Java7, and attach corresponding code examples. 1. Overview: The thread pool is a multi-thread processing structure that can reuse a fixed number of threads to avoid frequent creation and

How to use the ExecutorCompletionService function in Java for thread pool task scheduling How to use the ExecutorCompletionService function in Java for thread pool task scheduling Jun 26, 2023 pm 02:49 PM

With the development of Internet technology, the importance of multi-threaded programming has become increasingly prominent. When writing high-concurrency programs, making full use of multi-threading technology can greatly improve the execution efficiency of the program. However, multi-threaded programming itself involves many issues, such as communication between threads, synchronization cooperation, etc. In order to solve these problems, Java provides many thread pool frameworks, among which ExecutorCompletionService is one of them. This article will introduce ExecutorCompletionServi

How to handle service thread pool and task scheduling in microservice architecture? How to handle service thread pool and task scheduling in microservice architecture? May 17, 2023 am 08:36 AM

With the widespread application of microservice architecture in enterprise-level applications, how to optimize the performance and stability of microservices has become the focus of attention. In microservices, a microservice may handle thousands of requests, and the service's thread pool and task scheduling are also important components of microservice performance and stability. This article will introduce thread pools and task scheduling in microservice architecture, and how to optimize the performance of thread pools and task scheduling in microservices. 1. Thread pool in microservice architecture In microservice architecture, each request processed by microservice will occupy its thread pool.

How to use thread pool to implement priority scheduling of tasks in Java 7 How to use thread pool to implement priority scheduling of tasks in Java 7 Jul 30, 2023 pm 06:38 PM

How to use thread pools to implement task priority scheduling in Java7 In concurrent programming, task priority scheduling is a common requirement. Java provides a thread pool mechanism that allows us to easily manage and schedule tasks. This article will introduce how to use the thread pool to implement task priority scheduling in Java7. First, we need to understand the basic concepts and usage of thread pools in Java7. A thread pool is a thread reuse mechanism that manages and schedules a group of threads to perform multiple tasks. Java mention

Where is the spring thread pool configured? Where is the spring thread pool configured? Jan 19, 2024 pm 04:55 PM

Methods to configure the spring thread pool: 1. Use ThreadPoolTaskExecutor Bean; 2. Use SimpleAsyncTaskExecutor; 3. Use TaskExecutor Bean in XML; 4. Use third-party libraries; 5. Customize the implementation; 6. Configure through system properties or environment variables; 7. Integration and containers; 8. Programmatic configuration; 9. Integration using third-party frameworks; 10. Hybrid configuration; 11. Consider resource limitations and constraints, etc.

How to implement Springboot's own thread pool How to implement Springboot's own thread pool Jun 28, 2023 pm 04:33 PM

1: ThreadPoolTaskExecuto1 ThreadPoolTaskExecutor Thread pool: ThreadPoolTaskExecutor is a secondary encapsulation of Spring based on Java's own thread pool ThreadPoolExecutor. The main purpose is to make it more convenient to use thread pools in the spring framework system. It is the default thread pool in Spring 2. Use ThreadPoolTaskExecutor to inject beans Go to the configuration file form in ioc, Spring will automatically configure ##Default thread pool configuration, ThreadPoolTaskExecutor#Core

See all articles