Alibaba specification: the effect will be better if you manually create a thread pool. The solution is to manually create a thread pool ThreadPoolExecutor

Create thread pool manually

When using Executors to create threads, Alibaba specification proposes to manually create thread pools, which will have a better effect. Using ThreadPoolExecutor to create a thread pool can avoid the risk of resource exhaustion (OOM)

Constructor for ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;

Alibaba specification warning information

Thread pool not allowed Executors To create, but through ThreadPoolExecutor This processing method makes the writing students more clear about the running rules of the thread pool and avoid the risk of resource depletion. explain: Executors The disadvantages of the returned thread pool object are as follows:
1)FixedThreadPool and SingleThreadPool:
  The allowed request queue length is Integer.MAX_VALUE,A large number of requests may accumulate, resulting in OOM. 
  The number of creation threads allowed is Integer.MAX_VALUE,A large number of threads may be created, resulting in OOM. 
Positive example 1: 
    ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
        new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
Positive example 2: 
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()

    //Common Thread Pool
    ExecutorService pool = new ThreadPoolExecutor(5, 200,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    pool.execute(()-> System.out.println(Thread.currentThread().getName()));
    pool.shutdown();//gracefully shutdown
Positive example 3: 
    <bean id="userThreadPool"
        <property name="corePoolSize" value="10" />
        <property name="maxPoolSize" value="100" />
        <property name="queueCapacity" value="2000" />

    <property name="threadFactory" value= threadFactory />
        <property name="rejectedExecutionHandler">
            <ref local="rejectedExecutionHandler" />
    //in code

Logic diagram and description of thread execution

Logic diagram

Logical description

  • Judge whether the number of core threads is full. The number of core threads is related to the corePoolSize parameter
  • If the core thread pool is full, judge whether the queue is full. Whether the queue is full is related to the workQueue parameter
  • If the queue is full, judge whether the thread pool is full. Whether the thread pool is full is related to the maximumPoolSize parameter
  • If the thread pool is full, the task that cannot be executed is handled by the reject policy, which is related to the handler parameter

Parameter description of construction method of ThreadPoolExecutor:

  • Corepoolsize = > the number of core threads in the thread pool. It determines whether to create a new thread for execution or throw it into the workQueue task queue
  • Maximumpoolsize = > maximum number of thread pools. This parameter determines the maximum number of thread pools created according to the type of workQueue task queue you use
  • Keepalivetime = > idle thread lifetime. When the number of idle threads exceeds the corePoolSize, the redundant threads will be destroyed when the lifetime expires
  • Unit = > time unit, the time unit of keepAliveTime
  • Workqueue = > the task queue used by the thread pool, which is added to the thread pool but has not been executed; It is generally divided into direct submission queue, bounded task queue, unbounded task queue and priority task queue
  • Threadfactory = > the factory, factory name, etc. used by the thread pool to create threads. It is generally used by default
  • Handler = > the processing strategy of the thread pool for rejecting tasks. How to reject tasks when there are too many tasks

We can use the Alibaba specification to create threads

Complete code


import cn.hutool.core.thread.ThreadFactoryBuilder;
import java.util.concurrent.*;

public class Thread01 {
    public static void main(String[] args) {
        // Write the name of the thread. Generally, you can use the default,
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
        ExecutorService pool = new ThreadPoolExecutor(2, 200,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024),namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        // Calling thread
        for (int i = 0; i < 4; i++) {

Tags: Multithreading

Posted on Sun, 05 Dec 2021 00:24:05 -0500 by tony-kidsdirect