Java thread pool ThreadPoolExecutor
Java provides four thread pools through Executors:
NewCachedThreadPool creates a cache thread pool. If the thread pool length exceeds the processing requirement, Idle threads can be recycled flexibly. If no thread pool length exists, a new thread is created.
NewFixedThreadPool creates a fixed-length thread pool, which can control the maximum number of concurrent threads. threads that exceed the limit will wait in the queue.
NewScheduledThreadPool creates a fixed-length thread pool that supports scheduled and periodic task execution.
NewSingleThreadExecutor creates a single-threaded thread pool. It only uses a unique worker thread to execute tasks, ensuring that all tasks are executed in the specified Order (FIFO, LIFO, priority.
Familiar with these four thread pools, first understand ThreadPoolExecutor
ThreadPoolExecutor defines the following attributes that are important:
CorePoolSize: Number of threads in the thread pool. By default, several threads are enabled in the thread pool to process tasks in the task queue.
(Note: This is not fixed. It is changed based on the different implementation types of the queue (workQueue)
MaximumPoolSize: the maximum number of threads in the thread pool. This attribute is in conflict with the corePoolSize above. It indicates that the thread data is defined above. How can this problem be further controlled?
The maximum number of threads is actually the same as the above mentioned (this attribute must be used for corresponding task denial policies based on different implementation types of the queue (workQueue)
KeepAliveTime; // The time during which Idle threads that exceed corePoolSize will be destroyed
TimeUnit unit; // The unit of keepAliveTime
BlockingQueue <Runnable> workQueue: task queue, submitted but not executed
There are the following implementation types:
SynchronousQueue: a queue submitted directly. The queue has no capacity. Each clean operation corresponds to a corresponding delete operation, and each delete operation corresponds to a corresponding insert operation.
SynchronousQueue does not save the task. It always submits the task to the thread for execution. If there is no idle process, it tries to create a new process.
If the maximum number of threads set by maximumPoolSize is reached, a denial policy is executed.
ArrayBlockingQueue: A Bounded task queue. The ArrayBlockingQueue constructor must contain a capacity parameter (for example, n), which indicates the maximum capacity of the queue.
When a new task is executed, the current number of threads is defined as t. The capacity parameter of the constructor is n, and the length of the current queue is l.
1. t <corePoolSize, create a new thread heart
2. t> when corePoolSize and l <n, It is inserted into the task queue, waiting for execution by Idle threads.
3. t> corePoolSize and l> = n, a new thread is created to execute a new task.
4. t> when maximumPoolSize is used, a denial policy is executed.
LinkedBlockingQueue: unbounded task queue. When a new task is executed, if the number of threads in the thread pool is smaller than corePoolSize, a new thread is created. Otherwise, the queue is waiting.
If no task is created and the processing speed is significantly different, the unbounded queue will keep increasing rapidly until the system memory is exhausted.
PriorityBlockingQueue: priority queue, which can control the execution sequence of tasks. It is a special unbounded queue. No matter the bounded queues are unbounded queues, they all follow the first-in-first-out algorithm.
This queue can be used to handle tasks in order of priority.
ThreadFactory threadFactory // thread factory, used to create a thread. The default value is
RejectedExecutionHandler handler; // The denial policy. How can I reject a task when the task is too late to be processed?
The built-in denial policy of JDK is as follows:
AbortPolity policy: this policy directly throws an exception to prevent the system from working properly.
CallerRunsPolity policy: as long as the thread is closed, this policy runs the currently discarded task directly in the caller's thread.
DiscardOledstPolicy: this policy discards the oldest request, that is, a task to be executed, and tries to submit the current task again.
DiscardPlicy policy: this policy silently discards tasks that cannot be processed and does not process them.
If the preceding policies cannot meet the actual application requirements, you can extend the RejectedExecutionHandler interface.
public interface RejectedExecutionHandler { void rejectedExecution(Runnable r, ThreadPoolExecutor executor);}
Here, r is the request execution task, and executor is the current thread pool.
After learning about the preceding attributes of ThreadPoolExecutor, it is easy to analyze the four thread pools provided by Executors.
Executors. newFixedThreadPool (nThreads)
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
Return a corePoolSize, maximumPoolSize equal to the size of the thread pool that uses the queue blockingqueue task queue, because for a fixed size thread pool, there is no dynamic number of threads
Therefore, corePoolSize can be equal to maximumPoolSize. At the same time, it uses an unbounded queue to store tasks that cannot be executed immediately. When the task is submitted very frequently, the queue may rapidly expand and thus run out.
System resources.
Executors. newSingleThreadExecutor ()
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
Returns the thread pool of a single thread, which is a degradation of the newFixedThreadPool () method, but simply sets the number of threads in the thread pool to 1.
Executors. newCachedThreadPool ()
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
Return the thread pool with the corePoolSize of 0 maximumPoolSize infinity, which means that when there is no task, the thread is wireless, and when the task is submitted, the thread pool uses Idle threads to execute tasks.
Thread, the task is added to the SynchronousQueue queue, while the SynchronousQueue queue is a directly submitted queue, which always forces the thread pool to add a new thread to execute the task. After the task is completed,
Because corePoolSize is 0, empty threads are recycled within the specified time (60 s.
For newCachedThreadPool (), if a large number of tasks are submitted at the same time, and the execution of the task is not so fast, the system will enable equivalent thread processing, this approach may quickly exhaust system resources.