NewCachedThreadPool
Create a thread pool where new threads can be created as needed, but they will be reused when previously constructed threads are available. For programs that execute many short-term asynchronous tasks, these thread pools can usually improve program performance. Calling execute will reuse the previously constructed thread (if the thread is available ). If the existing thread is not available, create a new thread and add it to the pool. Terminate and Remove unused threads from the cache for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note: You can use the ThreadPoolExecutor constructor to create a thread pool with similar attributes but different details (such as timeout parameters.
The reprinted content is as follows:
ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime,
TimeUnit unit, BlockingQueue WorkQueue, RejectedExecutionHandler handler)
CorePoolSize: Minimum number of threads maintained by the thread pool maximumPoolSize: Maximum number of threads maintained by the thread pool keepAliveTime: the idle time allowed by the thread pool maintenance thread
Unit: the unit of idle time allowed by the thread pool to maintain the thread. workQueue: The Buffer Queue handler used by the thread pool: The processing policy of the thread pool to reject tasks.
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:
L 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. That is, the processing task priority is: Core Thread corePoolSize, task queue workQueue, maximumPoolSize. If all three are full, handler is used to process the rejected task.
5. 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.
An ExecutorService that uses one of several possible pool threads to execute each submitted task. It is usually configured using the Executors factory method.
The thread pool can solve two different problems: because it reduces the overhead of each task call, they can generally provide enhanced performance when executing a large number of asynchronous tasks, you can also bind and manage resources (including the threads used to execute collection tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
This class provides many adjustable parameters and extension hooks for ease of use across a large number of contexts. However, it is strongly recommended that programmers use the more convenient Executors factory method Executors. newCachedThreadPool () (unbounded thread pool, which can be automatically recycled), Executors. newFixedThreadPool (int) (fixed-size thread pool) and Executors. newSingleThreadExecutor () (a single background thread), which are predefined for most use cases. Otherwise, use the following instructions when manually configuring and adjusting the class:
Core and maximum pool size
ThreadPoolExecutor automatically adjusts the pool size based on the boundaries set by corePoolSize (see getCorePoolSize () and maximumPoolSize (see getMaximumPoolSize. When a new task is submitted in the execute (java. lang. Runnable) method, if the running thread is less than corePoolSize, a new thread is created to process the request, even if other auxiliary threads are idle. If the number of running threads is greater than corePoolSize and less than maximumPoolSize, a new thread is created only when the queue is full. If the set corePoolSize and maximumPoolSize are the same, a fixed thread pool is created. If you set maximumPoolSize to a basic unbounded value (such as Integer. MAX_VALUE), the pool is allowed to adapt to any number of concurrent tasks. In most cases, the core and maximum pool sizes are only set based on the constructor. However, you can also use setCorePoolSize (int) and setMaximumPoolSize (int) for dynamic changes.
Construct on demand
By default, you can use the prestartCoreThread () or prestartAllCoreThreads () method to dynamically override the Core Thread created and started only when the new task is required.
Create a thread
Use ThreadFactory to create a new thread. Otherwise, Executors. defaultThreadFactory () is used to create threads in the same ThreadGroup, and these threads have the same NORM_PRIORITY priority and non-daemon status. By providing different ThreadFactory, you can change the thread name, thread group, priority, and daemon status. If ThreadFactory fails to create a thread when return null from newThread, the execution program continues to run, but cannot execute any tasks.
Maintain activity time
If there are more threads in the pool than corePoolSize, these extra threads will be terminated when the idle time exceeds keepAliveTime (see getKeepAliveTime (java. util. concurrent. TimeUnit )). This provides a way to reduce resource consumption when the pool is inactive. If the pool becomes more active later, a new thread can be created. You can also use setKeepAliveTime (long, java. util. concurrent. TimeUnit) to dynamically change this parameter. Use the value of Long. MAX_VALUE TimeUnit. NANOSECONDS to effectively disable idle threads from the previous termination status before closing.
Queuing
All BlockingQueue can be used to transfer and maintain submitted tasks. You can use this queue to interact with the pool size:
A. If the number of running threads is less than corePoolSize, Executor always prefers to add new threads without queuing.
B. If the running thread is equal to or greater than corePoolSize, Executor always prefers to add requests to the queue without adding new threads.
C. If the request cannot be added to the queue, a new thread is created, unless the creation of this thread exceeds the maximumPoolSize. In this case, the task is denied.
There are three common queuing policies:
Submit directly. The default Job Queue option is SynchronousQueue, which directly submits tasks to the thread without holding them. If there is no thread that can be used to run the task immediately, trying to add the task to the queue will fail, so a new thread will be constructed. This policy prevents locking when processing a collection of requests that may have internal dependencies. Direct submission usually requires unbounded maximumPoolSizes to avoid rejecting new tasks. This policy allows unbounded threads to grow when the command arrives continuously beyond the average number that the queue can handle.
Unbounded queues. The use of unbounded queues (for example, blockingqueue with no predefined capacity) will cause new tasks to be added to the queue when all corePoolSize threads are busy. In this way, the created thread will not exceed the corePoolSize. (Therefore, the value of maximumPoolSize is invalid .) When each task is completely independent from other tasks, that is, the task execution does not affect each other, it is applicable to the use of unbounded queues; for example, in the Web Page Server. This kind of queuing can be used to handle transient bursts of requests. This policy allows unbounded threads to grow when the command arrives continuously beyond the average number that the queue can handle.
Bounded queue. When a limited number of maximumPoolSizes are used, a bounded Queue (such as ArrayBlockingQueue) helps prevent resource depletion, but may be difficult to adjust and control. The queue size and the maximum pool size may need to be compromised: using large queues and small pools can minimize CPU usage, operating system resources, and context switching overhead, but may cause manual throughput reduction. If the tasks are frequently congested (for example, if they are I/O boundaries), the system may schedule a longer time than you permit for more threads. Using a small queue usually requires a large pool size, and the CPU usage is high, but it may encounter unacceptable scheduling overhead, which will also reduce the throughput.
Rejected task
When the Executor has been disabled and the Executor uses the finite boundary for maximum thread and work queue capacity, and is saturated, execute (java. lang. runnable. In both cases, the execute method calls the RejectedExecutionHandler's RejectedExecutionHandler. rejectedExecution (java. lang. Runnable, java. util. concurrent. ThreadPoolExecutor) method. The following provides four predefined handler policies:
A. in the default ThreadPoolExecutor. AbortPolicy, A running RejectedExecutionException will be thrown if the handler is rejected.
B. In ThreadPoolExecutor. CallerRunsPolicy, the thread calls the execute itself that runs the task. This policy provides a simple feedback control mechanism to speed down the submission of new tasks.
C. In ThreadPoolExecutor. DiscardPolicy, tasks that cannot be executed will be deleted.
D. In ThreadPoolExecutor. DiscardOldestPolicy, if the execution program is not closed, the task in the Job Queue header will be deleted, and then the execution program will be retried (if the execution fails again, the process will be repeated ).
Defining and using other types of RejectedExecutionHandler classes is also possible, but you need to be very careful when doing so, especially when the policy is only used for a specific capacity or queuing policy.
Hook method
This class provides the rewritable beforeExecute (java. lang. thread, java. lang. runnable) and afterExecute (java. lang. runnable, java. lang. throwable) method. These two methods are called before and after each task is executed. They can be used to manipulate the execution environment; for example, reinitializing ThreadLocal, collecting statistics, or adding log entries. In addition, you can override the terminated () method to execute all the special processing that needs to be completed after the Executor is completely terminated.
If an exception is thrown by the hook or callback method, the Internal auxiliary thread will fail and terminate suddenly.
Queue Maintenance
The getQueue () method allows access to the work queue for monitoring and debugging purposes. It is strongly opposed to using this method for any other purpose. Remove (java. lang. Runnable) and purge () methods can be used to help with storage collection when a large number of queued tasks are canceled.