java thread pool details

1, Benefits of using thread pools

  1. Reduce resource consumption: reduce the loss caused by thread creation and destruction by reusing the created threads.
  2. Improve response speed: when the number of threads in the thread pool does not exceed the maximum limit of the thread pool, some threads are waiting to allocate tasks. When tasks come, they can be executed without creating new threads.
  3. Improve thread manageability: the thread pool will optimize the threads in the pool according to the current system characteristics, and use the thread pool to uniformly allocate threads, which can avoid wireless creation and destruction of threads, and improve resource utilization and system stability.

2, Common creation methods of thread pool

  1. Created by the Executors factory method.
  2. new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long)
    keepAliveTime, TimeUnit unit, BlockingQueue
    workQueue) custom creation.

3, Explain Executors factory method creation

  1. newCachedThreadPool: create a cacheable thread pool. If the length of the thread pool exceeds the processing needs, you can flexibly recycle idle threads. If there is no recyclable thread, you can create a new thread.

    ExecutorService es3 = Executors.newCachedThreadPool();
            for (int i = 0; i < 20; i++) {
                es3.submit(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + "Task in progress");
                    }
                });
            }
    
  2. newFixedThreadPool: create a fixed length thread pool to control the maximum concurrent number of threads. The exceeded threads will wait in the confrontation.

    ExecutorService es2 = Executors.newFixedThreadPool(3);
            for (int i = 0; i < 10; i++) {
                es2.submit(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + "Task in progress");
                    }
                });
            }
    
  3. newScheduledThreadPool: create a fixed length thread pool. Support set and periodic people to implement.

    ScheduledExecutorService es4 = Executors.newScheduledThreadPool(2);
            System.out.println("Time:" + System.currentTimeMillis());
            for (int i = 0; i < 5; i++) {
                es4.schedule(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("Time:"+System.currentTimeMillis()+"--"+Thread.currentThread().getName() + "Task in progress");
                    }
                },3, TimeUnit.SECONDS);
            }
    
  4. Newsinglethreadexecution: create a singleton thread pool. It will only use a unique working thread to execute tasks to ensure all tasks.

    	ExecutorService es1 = Executors.newSingleThreadExecutor();
            for (int i = 0; i < 10; i++) {
                es1.submit(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + "Task in progress");
                    }
                });
            }
    

Note: there is an article in the concurrent programming section of Alibaba Development Manual: thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor. The reason is that when the thread exceeds the limit, it is easy to cause oom exceptions (OOM: memory overflow) and resource depletion.

4, Explain ThreadPoolExecutor custom creation

It is recommended to create a thread pool in this way. The created thread pool has no disadvantages. The bottom layer of Executors is ThreadPoolExecutor.

  1. Creation method:
new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable>
    workQueue)
  1. Detailed explanation of seven parameters:

(1) corePoolSize[5]: the number of core threads, which always exist, unless allowCoreThreadTimeOut. The number of threads ready after the thread pool is created, waiting to receive asynchronous tasks for execution. Equivalent to 5 threads, thread = new thread(); thread. start();
(2) maximumPoolSize[200]: maximum number of threads, specifies the maximum number of threads in the thread pool, and controls resources.
(3) keepAliveTime: survival time. If the number of currently running threads is greater than the number of cores, free the idle threads (maximumpoolsize corepoolsize) as long as the thread idle is greater than the specified keepAliveTime.
(4) Unit: time unit.
(5) BlockingQueue < runnable > workqueue: block the queue. If there are many tasks, many tasks will be put in the queue. As long as there are threads idle, they will go to the queue to take out new tasks to continue execution.
(6) ThreadFactory: a factory created by a thread.
(7) Rejectedexecutionhandler: if the queue is full, reject execution according to the rejection policy specified by us.

  1. Work sequence and process

(1) Create a thread pool, prepare the number of core threads with corePoolSize, and prepare to accept tasks;
(2) When all the core threads are in use, they put the incoming tasks into the blocking queue. Idle core threads will block the queue to get task execution;
(3) When the blocking queue is full, new threads are directly opened for execution. The maximum number of threads can only be opened to the maximum poolsize;
(4) When the maximum number of threads is full, reject the task with RejectedExecutionHandler;
(5) The maximum threads are completed and there are many idle threads. After the specified time keepAliveTime, free the idle threads (max core).

  1. Take a chestnut
    How is a thread pool core 7, max 20, queue 50, 100 allocated when concurrent threads come in?
ThreadPoolExecutor executor = new ThreadPoolExecutor(
                5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

A: seven will be implemented immediately. 50 threads enter the queue and 13 threads are opened for execution,The remaining 30 use the reject strategy.

Keywords: Java Back-end

Added by mlai4167 on Fri, 10 Dec 2021 14:37:55 +0200