Thread Pool (knowledge point)

Source: Internet
Author: User

Fixed Thread Pool
Public static ExecutorService newFixdThreadPool (int size );
This method generates a thread pool with a fixed size. If a thread is aborted abnormally, a new thread is generated to replace it. The parameter size is used to indicate the size of the thread pool.
Public static ExecutorService newSingleThreadExecutor ();
This method creates a thread pool, a bit like newFixdThreadPool (1). Only one task can be executed at the same time, and multiple tasks can be executed sequentially, and it cannot be reconfigured to support multiple threads. If the thread is aborted abnormally, a new thread is generated to replace it.
Both methods return references of the ExecutorService interface type. In fact, this reference points to the thread pool object. You can use the ExecutorService reference to call its execute method to use the thread in the thread pool to execute the specified task. The detailed parameters of the execute method are given below:
Public void execute (Runnable command );
The command parameter points to the Runnable interface object, and the code in the next object run method describes the task to be executed.
 
If you want the program to exit after running all the tasks, you need to call the shutdown method in the ExecutorService interface to close the thread pool. The following lists two methods to close the thread pool:
Public void shutdown ();
This method closes the thread pool and no longer accepts new tasks. When the old task ends, all threads in the pool are closed.
Public void shutdownNow ();
This method immediately closes the thread pool no matter whether all tasks are completed, and the List is the waiting task.
Variable-size Thread Pool
Public static ExecutorService newCacheTheadPool ();
This method creates a thread pool with a variable thread pool size. When executing a task, it selects to reuse existing Idle threads in the cache to complete the task. If there is no idle thread, a new thread is created, threads idle for more than 60 seconds will be deleted from the thread pool.
Delay Thread Pool
In actual development, it is sometimes necessary to let the specified Thread be executed after a specific delay. Using the delay thread pool provided in Java can well meet this requirement. Similarly, the delayed thread pool is created by calling the static factory method of the Executor class. The following lists two static methods for creating the delayed thread pool:
Public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize );
This method creates a thread pool to execute specified tasks at a certain latency. The corePoolSize parameter is used to indicate the number of threads in the thread pool.
Public static ScheduledExecutorService newSingleThreadScheduledExecutor ();
This method is used to create a single-thread pool for latency, that is, the delayed thread pool created using this method has only one standby thread.
The ScheduledExecutorService interface inherits the ExecuteService interface and has all the methods of the ExecuteService interface.
The ScheduledExecutorService interface has its unique schedule method to delay the execution of the specified task:
Public ScheduledFuture schedule (Runnable runnable, long delay, TimeUnit unit );
This method mobilizes threads in the thread pool to execute specified tasks at a certain latency. the runnable parameter indicates the task to be executed, and the delay parameter indicates the length of the latency, the unit parameter indicates the time unit of the latency. The Return Value Type of this method is ScheduledFuture, which is used to store the result information of a task with returned results.
Custom parameter Thread Pool
If the above thread pools cannot meet our needs, we can consider using the ThreadPoolExecutor class to implement a custom thread pool, which has a built-in thread Queue (BlockingQueue ).
The inheritance relationships of ThreadPoolExecutor are as follows:
Executor-> ExecutorService-> AbstractExecutorService-> ThreadPoolExecutor
Core pool size, maximum pool size, and keep-alive time jointly manage thread creation and destruction.
The thread pool class is java. util. concurrent. ThreadPoolExecutor. The common constructor is as follows:
Java code
Public ThreadPoolExecutor (int corePoolSize,
 
Int maximumPoolSize,
 
Long keepAliveTime,
 
TimeUnit unit,
 
BlockingQueue <Runnable> workQueue,
 
RejectedExecutionHandler handler ){
 
This (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
 
Executors. defaultThreadFactory (), handler );
 
}
CorePoolSize: the minimum number of threads maintained by the thread pool, even if idle.
MaximumPoolSize: Maximum number of threads maintained by the thread pool.
KeepAliveTime: the idle time allowed by the thread pool to maintain the thread.
Unit: the unit of idle time allowed by the thread pool to maintain the thread.
WorkQueue: The Buffer Queue used by the thread pool. The length of the Buffer Queue determines the maximum number of buffered queues.
Reject a task: a task that is attempted to be added when the number of threads in the thread pool reaches maximumPoolSize and the workQueue queue is full.
Handler: The processing policy of the thread pool to reject tasks. Four handler policies are defined in ThreadPoolExecutor:
1. CallerRunsPolicy: this policy retries to add the current task. It will automatically repeat the execute () method until it is successful.
2. AbortPolicy: discard a denial task and throw an exception.
3. DiscardPolicy: the denial task is directly discarded without any exception information.
4. DiscardOldestPolicy: instead of abandoning a denial task, DiscardOldestPolicy discards the thread waiting for the longest time in the queue and adds the denial task to the queue.
 
A task is added to the thread pool using the execute (Runnable) method. A task is a Runnable object. The execution method of a task is the run () method of a Runnable object.
When a task is added to the thread pool through the execute (Runnable) method, the thread pool adopts the following policy:
1. If the number of threads in the thread pool is smaller than corePoolSize at this time, a new thread should be created to process the added tasks even if all threads in the thread pool are idle.
2. If the number in the thread pool is equal to corePoolSize, but the Buffer Queue workQueue is not full, the task is put into the buffer queue.
3. If the number in the thread pool is greater than corePoolSize, the Buffer Queue workQueue is full, and the number in the thread pool is smaller than maximumPoolSize, a new thread is created to process the added task.
4. If the number in the thread pool is greater than corePoolSize, the Buffer Queue workQueue is full, and the number in the thread pool is equal to maximumPoolSize, the handler policy is used to process the task.
The priority of the processing task is:
Core Thread corePoolSize, task queue workQueue, and maximumPoolSize. If all three are full, handler is used to process the rejected task. When the number of threads in the thread pool is greater than corePoolSize, if the idle time of a thread exceeds keepAliveTime, the thread will be terminated. In this way, the thread pool can dynamically adjust the number of threads in the pool.
After understanding the above introduction to ThreadPoolExecutord, we should be able to understand some of its usage. However, there is a key Worker class in ThreadPoolExocutor, and all threads must be packaged by Worker. In this way, threads can be reused without re-creating threads.
At the same time, the Executors class contains several methods such as newFixedThreadPool () and newCachedThreadPool (). In fact, ThreadPoolExocutor is indirectly called, but different construction parameters are passed.

 

Author "xiehongdong"
 

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.