Principle of thread pool and custom thread pool

Keywords: Java Multithreading

Thread pool execution principle and custom thread pool

Thread pool execution principle:

Daily record
(1) . advantages of using thread pool:
     Application of pooling Technology: thread pool, database connection pool, http connection pool, etc.

     The idea of pooling technology is mainly to reduce the consumption of resources and improve the utilization of resources.

     Thread pool provides a strategy to limit and manage resources. Each thread pool also maintains some basic statistics, such as the number of completed tasks.

(2) . benefits of using thread pool:

     Reduce resource consumption: reduce the consumption caused by thread creation and destruction by reusing the created threads.

     Improve response speed: when a task arrives, it can be executed immediately without waiting for thread creation.

     Improve the manageability of threads: threads are scarce resources. If they are created without restrictions, they will not only consume system resources, but also reduce the stability of the system. Using thread pool can carry out unified allocation, monitoring and tuning.

ThreadPoolExecutor: upper level relationship

Execution process:
Thread pool execution diagram:

Thread pool execution order:
Threads in the thread pool are executed by the executos() method to create threads. When the number of resident threads in the thread pool is too large to handle, more than requests will be stored in the blocking queue
, when the queue is blocked and the storage request is full, a new thread will be re created in the thread pool, and too many requests that cannot be stored in the queue will be handled by the newly created thread
If the number of requests is greater than the maximum number of threads in the thread pool, the thread will execute the reject policy (four types)

  1. AbortPolicy: reject, request too many task policies, and throw an exception: RejectedExecutionException
  2. CallerRunsPolicy: return the requested task to the caller
  3. DiscardOldestPolicy: discard the queue, wait for the longest request task, and then add the current task to the queue for processing
  4. DiscardPolicy: discards the request task that cannot be processed without any processing

Custom thread pool:

Create thread pool without JDK Executors reason:
1.FixedThreadPool and SingleThreadPool:
The allowed request queue length is Integer.MAX_VALUE, which may accumulate a large number of requests, resulting in OOM (memory overflow)
2.CachedThreadPool and ScheduledThreadPool:
The number of threads allowed to be created is: Integer.MAX_VALUE, a large number of threads may be created, resulting in OOM
For details, please refer to Alibaba development manual

Custom thread pool demonstration:

import java.util.concurrent.*;

/**
 * Custom thread pool:
 *   To create a thread pool object:
 *     Thread pool basic, 7 parameters:
 *          1.Number of resident threads - corePoolSize
 *          2.Maximum number of threads - maximumPoolSize
 *          3.Thread death time - keepAliveTime
 *          4.Thread death time unit - deadTime (TimeUnit.)
 *          5.Blocking queue - BlockingQueue < runnable >
 *          6.Rejection policy - RejectedExecutionHandler (four policies)
 *          7.Thread factory - ThreadFactory
 *
 *    Thread pool execution process:
 *          Threads in the thread pool are executed by the executos() method to create threads. When the number of resident threads in the thread pool cannot process requests, more than requests will be stored in the blocking queue
 *          ,When the queue is blocked and the request is full, the thread will be re created in the thread pool, and too many requests that cannot be stored in the queue will be handled by the newly created thread
 *          ,If the number of requests is greater than the maximum number of threads in the thread pool, the thread will execute the reject policy (four types)
 *      Reject policy:
 *          AbortPolicy: Reject, request too many task policies, and throw an exception: RejectedExecutionException
 *          CallerRunsPolicy: Return the requested task to the caller
 *          DiscardOldestPolicy: Discard the queue, wait for the longest request task, and then add the current task to the queue for processing
 *          DiscardPolicy: Discard the request task that cannot be processed without any processing
 *
 *    Create thread pool without JDK Executors reason:
 *      1.FixedThreadPool And SingleThreadPool:
 *          The allowed request queue length is Integer.MAX_VALUE, which may accumulate a large number of requests, resulting in OOM (memory overflow)
 *      2.CachedThreadPool And ScheduledThreadPool:
 *          The number of threads allowed to be created is: Integer.MAX_VALUE, a large number of threads may be created, resulting in OOM
 */
public class CustomThreadPool {
    private static volatile int corePoolSize=2;//Number of resident thread pools
    private static volatile int maximumPoolSize=5;//Maximum number of thread pools
    private static volatile Long keepAliveTime=1L;//Extinction time
    private static volatile TimeUnit deadTime=TimeUnit.SECONDS;//Time unit
    private static final ArrayBlockingQueue<Runnable> arrayBlockingQueue=new ArrayBlockingQueue<>(4);//Number of storage request tasks
    private static final RejectedExecutionHandler rejectedExecutionHandler=new ThreadPoolExecutor.AbortPolicy();//Reject policy
    private static volatile ThreadFactory threadFactory = Executors.defaultThreadFactory();//Create default thread factory

    public static void main(String[] args) {

        //Create thread pool object
        ExecutorService executorService = new ThreadPoolExecutor(corePoolSize
                ,maximumPoolSize
                ,keepAliveTime
                ,deadTime
                ,arrayBlockingQueue
                ,threadFactory
                ,rejectedExecutionHandler);
        try {
            for (int i = 1; i <=100 ; i++) {
                executorService.execute(()->{
                    System.out.println("Current thread:"+Thread.currentThread().getName());
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //Be sure to release the thread
            executorService.shutdown();
        }
    }
}

Posted by toodi4 on Fri, 26 Nov 2021 19:47:53 -0800