Thread pool to achieve ThreadPoolExecutor

First, the purpose of using a thread pool

In actual use, the thread is occupied system resources, if not properly managed thread can easily lead to system problems. Therefore, the thread pool will be used in most framework to manage concurrent threads. Use a thread pool thread management mainly has the following advantages:

1, to reduce resource consumption: to reduce system losses as much as possible by multiplexing the threads and reduce the number of already existing thread closed;

2, there is provided the system response: by multiplexing threads, thread creation process is omitted, and therefore enhance the overall response speed of the system;

3, improve the manageability of threads: the thread is a scarce resource, if the unlimited creation, not only consumes system resources, but also reduce system stability, therefore, need to use the thread pool to manage threads.

Second, the composition of the thread pool

Generally a simple thread has at least the following components.

1, the thread manager (ThreadPoolManager): used to create and manage the thread pool;

2, the worker thread (workThread): pool threads in the thread;

3, the task Interface (Task): Each task must implement, for the implementation of thread scheduling tasks;

4, task queue: for storing task is not processed, provides a buffering mechanism.

Thread Pool Manager has at least the following features: create a thread pool, the destruction of the thread pool, add new tasks, create a thread pool. FIG follows:

Third, the composition of the thread pool

When a concurrent tasks submitted thread pool, thread pool threads are allocated to tasks shown in FIG procedure:

As can be seen from the figure, the thread pool to perform its mandate submitted by the main have several stages:

1, first determine the thread pool nuclear heart thread pool all the threads are all on a mission, if not, create a thread to perform tasks just submitted, otherwise, all threads in the thread pool are at the core mission, go to step 2 ;

2, determines whether the current blocking queue is not full, if not full, the task would be submitted in place of the blocking queue; in go to Step 3;

3, determine all the threads in the thread pool if are on a mission, if not, create a new thread to perform the task, or to saturation strategy for processing.

Fourth, create a thread pool

Create a thread pool is mainly ThreadPoolExecutor class to complete, there are many ways ThreadPoolExecutor overloaded, through which most of argument constructor thread pool to understand those parameters need to be configured, in particular:

 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 :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

The following parameters will be described:

1, corePoolSize: indicates the size of the thread pool, when submitting a job, if and when the pool of strong core number of threads does not reach corePoolSize, a new thread is created to perform tasks submitted, even if the current core thread pool has free thread, if the current number of threads in the thread pool has reached the core corePoolSize, no longer create a thread, if you call prestartCoreThread()or prestartAllCoreThreads() all of the core thread pool threads are created when they were created and launched.

2, maximumPoolSize: indicates that the thread pool can create the maximum number of threads. If blocked when the queue is full, and the current number of thread pool does not exceed maxmumPoolSize, it would create a new thread to perform the task.

3, keepAliveTime: idle thread survival time, such as over-current pool has exceeded the number of threads CorePoolSize, and the thread is idle for more than KeepAliveTime, it would idle thread will be destroyed, so as to reduce system resource consumption.

4, unit: unit of time specified unit of time is keepAliveTime.

5, workQueue: blocking queue, for storing task queue blocking, may be used ArrayBlockingQueue, LinkedBlockingQueue, SynchronousQueue, priorityBlockingQueue;

6, ThreadFactory: Creating engineering thread, a thread factory by specifying for each thread set out to create a more meaningful name. If problems arise, but also easy to find the cause of the problem.

7, handler: saturation strategy, blocking queue when the thread pool is full and the specified thread has been opened, indicating that the current thread pool is already saturated, then we need to adopt a strategy to deal with this situation, using strategies these types:

  • AbortPolicy: direct refusal task submitted and RejectedExecutionException throw an exception;
  • CallerRunsPolicy: only to perform tasks with the caller where the thread;
  • DiscardPolicy: do not deal directly lose tasks;
  • DiscardOldestPolicy: throw away the blocking queue storage longest task execution of the current task;

ThreadPoolExecutor execute method execution logic see comments. Performing a schematic diagram below shows the execute method of ThreadPoolExecutor:

Execute method execution logic has several situations:

1, if the currently running thread less and corePoolSize, it will create a new thread to perform new tasks;

2, if the number of running threads is equal to or greater than corePoolSize, the task will be submitted to the blocking queue stored in workQueue;

3, if the current workQueue queue is full, then this will create a new thread to perform the task;

4, if the number of threads has exceeded maximunPoolSize, will be handled with saturated strategy RejectedExecutionHandler;

It should be noted that the design of the thread pool is to use a core thread pool CorePoolSize, thread pools and blocking queues workQueue maxmumPoolSize, this caching strategy to handle the task, this design will be used in many frameworks.

Fifth, the thread pool is closed

Close the thread pool, you can shutdown and shutdownNow these two methods. Their principle is to traverse all of the threads in the pool, followed by an interrupt thread. Both differences are as follows:

1, shutdownNow first state of the thread pool is set to STOP, and then try to stop all the threads executing and not executing. And returns a list of tasks awaiting execution;

2, shutdown except that the state of the thread pool is set to shutdown state, and not being interrupted all the threads of execution.

As can be seen the task being performed shutdown method will continue to implement complete, and shutdownNow directly interrupt task is being executed. Call any one of these two methods, isshutdwon method returns true, when all the threads are closed successfully, it indicates that the thread pool is closed. This is the method call returns true isTerminated will.

Sixth, how to appropriately configure the thread pool parameters

To a reasonable allocation of the thread pool, you must first analyze task characteristics, can be analyzed from the following perspectives:

1, the nature of the task: CPU-intensive tasks, IO-intensive tasks and mixed tasks;

2, task priority: High, Low, Medium

3, task execution time: long, medium and short

4, the task dependency: if dependent on other system resources, such as database connections;

Published 21 original articles · won praise 4 · Views 503

Guess you like

Origin blog.csdn.net/weixin_39617728/article/details/105019782