Java multithreading -- ThreadPoolExecutor (thread pool)

Source: Internet
Author: User

Java multithreading -- ThreadPoolExecutor (thread pool)
What is a thread pool?

 

In multi-threaded development, because the number of threads is large and the execution of each thread ends for a period of time, frequent thread creation is required. However, frequent thread creation will greatly reduce the system efficiency, it takes time to frequently create and destroy threads. In this case, people want a thread that does not need to be destroyed after execution, and the thread can also execute other tasks. In this case, the thread pool will appear.

 

The thread pool is the thread pool. After a task is submitted to the thread pool, an idle thread is taken from the thread pool for service. After the service is completed, the thread is not destroyed, instead, return the thread back to the thread pool.

 

In the programming mode of the thread pool, the task is submitted to the entire thread pool, rather than directly to a thread. After the thread pool obtains the task, it finds any Idle threads internally, then, the task is handed over to an internal idle thread. If there is no idle process, the task is in the waiting state, which is encapsulation.

 

After the thread pool is used, the number of threads created and destroyed is reduced, and each thread can be reused to execute multiple tasks. At the same time, according to the capacity of the system, adjust the number of threads in the thread pool to avoid consumption of system memory.

 

 

ThreadPoolExecuto example

 

We first use a simple thread pool example to give a general understanding of ThreadPoolExecuto. We have constructed a normal thread count of 5 and a maximum thread pool of 10, the thread pool of task cache queue 5 allows this thread pool to run the demo of 15 tasks.

 

Let's take a look at the MyRunnable class to record the number of currently running tasks:

 

Package com. tgb. threadpool;/*** thread execution * @ author kang **/public class MyRunnable implements Runnable {// number of tasks being executed private int num; public MyRunnable (int num) {this. num = num;} @ Overridepublic void run () {System. out. println (MyRunnable + num being executed); try {Thread. currentThread (). sleep (4000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (MyRunnable + num + execution completed );}}

 

Thread Pool client:

 

Package com. tgb. threadpool; import java. util. concurrent. arrayBlockingQueue; import java. util. concurrent. threadPoolExecutor; import java. util. concurrent. timeUnit;/*** thread pool call client * @ author kang **/public class ThreadPoolExecutorTest {// Number of threads stored in the pool, including Idle threads. Final static int corePoolSize = 5; // maximum number of threads allowed in the pool. Final static int maximumPoolSize = 10; // when the number of threads is greater than the core thread, this is the maximum time for redundant Idle threads to wait for a new task before the termination of final static long keepAliveTime = 200; // keep the task queue 5 before execution, that is, the task cache queue final static ArrayBlockingQueue
 
  
WorkQueue = new ArrayBlockingQueue
  
   
(5); public static void main (String [] args) {// construct a thread pool. The number of normal threads is 5, and the maximum thread data is 10, wait time 200 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor (corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit. MINUTES, workQueue); // The thread pool executes 15 tasks for (int I = 0; I <15; I ++) {MyRunnable myRunnable = new myrunnable(imo-threadpoolexecutor.exe cute (myRunnable ); system. out. println (the number of threads in the thread pool is: + threadPoolExecutor. getPoolSize () +: the number of tasks waiting for execution in the queue is + threadPoolExecutor. getQueue (). size ();} // close the thread pool threadPoolExecutor. shutdown ();}}
  
 

 

Execution result:

 

The number of threads in the MyRunnable 0 thread pool being executed is: 1, and the number of tasks waiting for execution in the queue is: 2, the number of tasks waiting for execution in the queue is: 0. The current number of threads in the MyRunnable 1 thread pool being executed is: 3. The number of tasks waiting for execution in the queue is: 0: the number of threads in the MyRunnable 2 thread pool being executed is 4. The number of tasks waiting for execution in the queue is: 0. The number of threads in the MyRunnable 3 thread pool being executed is: 5. The number of tasks waiting for execution in the queue is: 0 MyRunnable 4. The current number of threads in the thread pool is: 5. The number of tasks waiting for execution in the queue is: 1. The number of threads in the thread pool is 5. The number of tasks waiting for execution in the queue is 5. The number of tasks waiting for execution in the queue is 5: 3. The current number of threads in the thread pool is 5. The number of tasks waiting for execution in the queue is 4. The current number of threads in the thread pool is 5. The number of tasks waiting for execution in the queue is: 5. The number of threads in the thread pool is 6. The number of tasks waiting for execution in the queue is 5. The number of MyRunnable 10 threads in the queue is 7, the number of tasks waiting for execution in the queue is: 5. The number of threads in the MyRunnable 11 thread pool being executed is: 8. The number of tasks waiting for execution in the queue is: 5. The current number of threads in the MyRunnable 12 thread pool being executed is 9, and the number of tasks waiting for execution in the queue is 5. The current number of threads in the MyRunnable 13 thread pool being executed is: 10. The number of tasks waiting for execution in the queue is: 5. MyRunnable 14: MyRunnable 0: Execution completed. MyRunnable 5: MyRunnable 3: Execution completed. MyRunnable 4: Execution completed. MyRunnable 2: Execution completed. MyRunnable 7: MyRunnable 6: Execution in progress listen 8 MyRunnable 1 execution completed MyRunnable 9 MyRunnable 12 execution completed MyRunnable 11 execution completed MyRunnable 10 execution completed MyRunnable 14 execution completed MyRunnable 13 execution completed MyRunnable 5 Execution completed MyRunnable 9 Execution completed MyRunnable 8. Execution completed. MyRunnable 6: Execution completed. MyRunnable 7: Execution completed.
According to the execution results, when the number of threads in the thread pool is greater than 5, the task is put into the task cache queue. When the task cache queue is full, a new thread is created for execution, if the number of tasks exceeds 15, the program will report an error and throw a task rejection exception. In this case, the task cache queue can be increased. If you are interested, you can try it.

 

 

Through this demo, we can have a macro understanding of the thread pool. Next we will continue to learn the ThreadPoolExecutor object in depth.

 

ThreadPoolExecutor source code

 

Java. uitl. concurrent. ThreadPoolExecutor is the core class in the thread pool. Therefore, we can further understand the thread pool by using the ThreadPoolExecutor source code:

 

public class ThreadPoolExecutor extends AbstractExecutorService {    // Public constructors and methods    /**     * Creates a new {@code ThreadPoolExecutor} with the given initial     * parameters and default thread factory and rejected execution handler.     * It may be more convenient to use one of the {@link Executors} factory     * methods instead of this general purpose constructor.     *     * @param corePoolSize the number of threads to keep in the pool, even     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set     * @param maximumPoolSize the maximum number of threads to allow in the     *        pool     * @param keepAliveTime when the number of threads is greater than     *        the core, this is the maximum time that excess idle threads     *        will wait for new tasks before terminating.     * @param unit the time unit for the {@code keepAliveTime} argument     * @param workQueue the queue to use for holding tasks before they are     *        executed.  This queue will hold only the {@code Runnable}     *        tasks submitted by the {@code execute} method.     * @throws IllegalArgumentException if one of the following holds:     *         {@code corePoolSize < 0}     *         {@code keepAliveTime < 0}     *         {@code maximumPoolSize <= 0}     *         {@code maximumPoolSize < corePoolSize}     * @throws NullPointerException if {@code workQueue} is null     */    public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue
 
   workQueue) {        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,             Executors.defaultThreadFactory(), defaultHandler);    }    /**     * Creates a new {@code ThreadPoolExecutor} with the given initial     * parameters and default rejected execution handler.     *     * @param corePoolSize the number of threads to keep in the pool, even     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set     * @param maximumPoolSize the maximum number of threads to allow in the     *        pool     * @param keepAliveTime when the number of threads is greater than     *        the core, this is the maximum time that excess idle threads     *        will wait for new tasks before terminating.     * @param unit the time unit for the {@code keepAliveTime} argument     * @param workQueue the queue to use for holding tasks before they are     *        executed.  This queue will hold only the {@code Runnable}     *        tasks submitted by the {@code execute} method.     * @param threadFactory the factory to use when the executor     *        creates a new thread     * @throws IllegalArgumentException if one of the following holds:     *         {@code corePoolSize < 0}     *         {@code keepAliveTime < 0}     *         {@code maximumPoolSize <= 0}     *         {@code maximumPoolSize < corePoolSize}     * @throws NullPointerException if {@code workQueue}     *         or {@code threadFactory} is null     */    public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue
  
    workQueue,                              ThreadFactory threadFactory) {        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,             threadFactory, defaultHandler);    }    /**     * Creates a new {@code ThreadPoolExecutor} with the given initial     * parameters and default thread factory.     *     * @param corePoolSize the number of threads to keep in the pool, even     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set     * @param maximumPoolSize the maximum number of threads to allow in the     *        pool     * @param keepAliveTime when the number of threads is greater than     *        the core, this is the maximum time that excess idle threads     *        will wait for new tasks before terminating.     * @param unit the time unit for the {@code keepAliveTime} argument     * @param workQueue the queue to use for holding tasks before they are     *        executed.  This queue will hold only the {@code Runnable}     *        tasks submitted by the {@code execute} method.     * @param handler the handler to use when execution is blocked     *        because the thread bounds and queue capacities are reached     * @throws IllegalArgumentException if one of the following holds:     *         {@code corePoolSize < 0}     *         {@code keepAliveTime < 0}     *         {@code maximumPoolSize <= 0}     *         {@code maximumPoolSize < corePoolSize}     * @throws NullPointerException if {@code workQueue}     *         or {@code handler} is null     */    public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue
   
     workQueue,                              RejectedExecutionHandler handler) {        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,             Executors.defaultThreadFactory(), handler);    }    /**     * Creates a new {@code ThreadPoolExecutor} with the given initial     * parameters.     *     * @param corePoolSize the number of threads to keep in the pool, even     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set     * @param maximumPoolSize the maximum number of threads to allow in the     *        pool     * @param keepAliveTime when the number of threads is greater than     *        the core, this is the maximum time that excess idle threads     *        will wait for new tasks before terminating.     * @param unit the time unit for the {@code keepAliveTime} argument     * @param workQueue the queue to use for holding tasks before they are     *        executed.  This queue will hold only the {@code Runnable}     *        tasks submitted by the {@code execute} method.     * @param threadFactory the factory to use when the executor     *        creates a new thread     * @param handler the handler to use when execution is blocked     *        because the thread bounds and queue capacities are reached     * @throws IllegalArgumentException if one of the following holds:     *         {@code corePoolSize < 0}     *         {@code keepAliveTime < 0}     *         {@code maximumPoolSize <= 0}     *         {@code maximumPoolSize < corePoolSize}     * @throws NullPointerException if {@code workQueue}     *         or {@code threadFactory} or {@code handler} is null     */    public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue
    
      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.corePoolSize = corePoolSize;        this.maximumPoolSize = maximumPoolSize;        this.workQueue = workQueue;        this.keepAliveTime = unit.toNanos(keepAliveTime);        this.threadFactory = threadFactory;        this.handler = handler;    }
    
   
  
 

 

Through the code, we found that ThreadPoolExecutor inherits the AbstractExecutorService class, inherits the AbstractExecutorService class, and provides four constructor methods, in fact, the first three constructor calls the initialization work of the fourth constructor.

 

Next, let's take a look at the definitions of parameters in the constructor, and add your own understanding with jdk-api:

 

CorePoolSize-number of core threads stored in the pool, including Idle threads. By default, after a thread pool is created, the number of threads in the thread pool is 0. When a task comes in, A thread will be created to execute the task. When the number of threads in the thread pool reaches corePoolSize, the tasks will be placed in the cache queue;

 

MaximumPoolSize-Maximum number of threads allowed in the pool.

 

KeepAliveTime-when the number of threads is greater than the number of cores, the thread terminates when no task is executed. By default, only when the number of threads in the thread pool is greater than the corePoolSize, keepAliveTime takes effect. If the number of threads in the thread pool is smaller than corePoolSize and the idle time of a thread reaches keepAliveTime, it is terminated.

 

Unit-the time unit of the keepAliveTime parameter. There are seven static attributes in the TimeUnit class:

 

TimeUnit. DAYS; // day TimeUnit. HOURS; // hour TimeUnit. MINUTES; // minute TimeUnit. SECONDS; // second TimeUnit. MILLISECONDS; // millisecond TimeUnit. MICROSECONDS; // The subtle TimeUnit. NANOSECONDS; // NANOSECONDS

WorkQueue-the queue used to keep tasks before execution, that is, the queue used to store tasks waiting for execution. This queue only keeps Runnable tasks submitted by the execute method. In general, we also call it a blocking queue. The selection of this parameter is also very important and will have a significant impact on the running process of the thread pool. We will introduce the blocking queue in the next article;

 

 

ThreadFactory-the factory used by the execution program to create a new thread;

 

Handler-the handler used to block execution because it exceeds the thread range and queue capacity. The following are common examples:

 

ThreadPoolExecutor. AbortPolicy: discard the task and throw an exception. ThreadPoolExecutor. DiscardPolicy: discard the task without throwing an exception. ThreadPoolExecutor. DiscardOldestPolicy: discard the task at the top of the queue and re-execute the task (repeat this process) ThreadPoolExecutor. CallerRunsPolicy: Call the thread to process the task.

Through code, we found that our ThreadPoolExecutor class inherits the AbstractExecutorService abstract class. Next, let's take a look at the AbstractExecutorService abstract class:

 

 

public abstractclass AbstractExecutorService implements ExecutorService {…………………………………………………..

 

The detailed code of the AbstractExecutorService class is no longer displayed. It implements the ExecutorService interface and provides the default implementation of the ExecutorService execution method. This class uses RunnableFuture returned by newTaskFor to implement the submit, invokeAny, and invokeAll methods.

 

Let's take a look at the ExecutorService interface:

 

public interfaceExecutorService extends Executor {………………………………………………….. 

The ExecutorService interface inherits the Executor interface. The ExecutorService interface is a real thread pool interface, and the ExecutorService can be closed, which causes it to reject new tasks. Two methods are provided to disable ExecutorService. The shutdown () method allows you to execute previously submitted tasks before termination, while the shutdownNow () method prevents waiting for the task to start and attempting to stop the currently running task. When the program is terminated, No task is being executed, No task is waiting for execution, and a new task cannot be submitted. Unused ExecutorService should be closed to allow recycling of its resources.

 

 

ExecutorService can also create and return a Future that can be used to cancel execution and/or wait for completion. The method submit extends the basic method Executor.exe cute (java. lang. Runnable ). Methods invokeAny and invokeAll are the most common methods for batch execution. They execute the collection task and then wait for at least one, or all tasks are completed (you can use the ExecutorCompletionService class to write Custom Variants of these methods ).

 

Next, let's look at the Executor interface.

 

public interface Executor {    /**     * Executes the given command at some time in the future.  The command     * may execute in a new thread, in a pooled thread, or in the calling     * thread, at the discretion of the {@code Executor} implementation.     *     * @param command the runnable task     * @throws RejectedExecutionException if this task cannot be     * accepted for execution     * @throws NullPointerException if command is null     */    void execute(Runnable command);}

This interface has only one execute method and executes the submitted Runnable task object. Therefore, the Executor interface is not a thread pool but a tool for executing the thread.

 

 

 

At this point, we should understand the relationship among ThreadPoolExecutor, AbstractExecutorService, ExecutorService, and Executor. Executor is the top-level interface used to execute thread tasks. The ExecutorService interface inherits the Executor interface, some methods are declared: submit, invokeAll, invokeAny, and shutDown. The abstract class actexecutorservice implements the ExecutorService interface and basically implements all the methods declared in the ExecutorService; finally, our ThreadPoolExecutor inherits the class AbstractExecutorService.

 

There are several common methods in our ThreadPoolExecutor class:

Execute (), submit (), shutdown (), shutdownNow (). For other methods, you can check the api

 

The execute () method is actually the method declared in the Executor. It is implemented in ThreadPoolExecutor. This method is the core method of ThreadPoolExecutor. You can submit a task to the thread pool through this method, it is executed by the thread pool.

 

The submit () method is the method declared in ExecutorService. The specific implementation of actexecutorservice has been completed. It is not overwritten in ThreadPoolExecutor, this method is also used to submit tasks to the thread pool, but it is different from the execute () method, it can return the results of task execution, to see the implementation of the submit () method, it will actually call the execute () method, but it uses the Future to obtain the task execution result.

 

Shutdown () and shutdownNow () are used to close the thread.

 

Summary

 

This article describes the ThreadPoolExecutor of the thread pool and the benefits of using the thread pool. It also provides a simple demo to give you an overall understanding of the thread pool, finally, the relationship between the ThreadPoolExecutor class and its parent class and interfaces is introduced. The introduction of ThreadPoolExecutor is here first.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.