Working principle
1, when the line Chengchigang is created, there is not a thread inside. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool will not execute them immediately.
2. When the Execute () method is invoked to add a task, the thread pool makes the following judgments:
A. If the number of threads running is less than corepoolsize, create a thread to run the task immediately;
B. If the number of threads running is greater than or equal to corepoolsize, put this task into the queue.
C. If the queue is full and the number of threads running is less than maximumpoolsize, create a thread to run the task;
D. If the queue is full and the number of threads running is greater than or equal to maximumpoolsize, the thread pool throws an exception telling the caller "I can't accept the task anymore".
3, when a thread completes the task, it takes the next task from the queue to execute.
4, when a thread has nothing to do, more than a certain amount of time (KeepAliveTime), the thread pool will determine if the current number of threads running more than corepoolsize, then the thread is stopped. So when all the tasks of the thread pool are complete, it eventually shrinks to the size of the corepoolsize.
Queued all blockingqueue are available for transmission and maintenance of submitted tasks. You can use this queue to interact with the pool size: If the running thread is less than corepoolsize, Executor always prefers to add new threads without queuing. If the thread that is running is equal to or greater than corepoolsize, Executor always prefers to join the queue without adding a new thread. If the request cannot be joined to the queue, a new thread is created unless the thread is created beyond maximumpoolsize, in which case the task is rejected. There are three common strategies for queuing: direct submission. The default option for the Task Force column is synchronousqueue, which is to submit the tasks directly to the thread without maintaining them. Here, if there is no thread available to run the task immediately, attempting to join the queue will fail, so a new thread is constructed. This policy avoids locking when processing a request set that may have internal dependencies. Direct submissions typically require unbounded maximumpoolsizes to avoid rejecting newly submitted tasks. This policy allows for the possibility of growth without a line when the command arrives continuously in excess of the averages that the queue can handle. unbounded queues. The use of unbounded queues (for example, linkedblockingqueue with no predefined capacity) will cause all corepoolsize threads to be busy waiting in the queue for a newer task. This creates a thread that does not exceed the corepoolsize. (therefore, the value of the maximumpoolsize is also invalid.) It is appropriate to use a unbounded queue when each task is completely independent of other tasks, that is, when task execution does not affect each other, for example, in a Web page server. This queuing can be used to handle transient burst requests, which allow for the possibility of growth without a boundary path when the command arrives continuously over the average number of times the queue can handle. bounded queues. When using limited maximumpoolsizes, bounded queues (such as arrayblockingqueue) help prevent resource depletion, but may be difficult to adjust and control. The queue size and maximum pool size may need to be compromised: the use of large queues and small pools minimizes CPU utilization, operating system resources, and context switching overhead, but can result in artificially low throughput. If tasks are frequently blocked (for example, if they are I/O boundaries), the system may schedule more threads than you would allow. Using small queues typically requires larger pool sizes, higher CPU usage, but may experience unacceptable scheduling overhead, which can also reduce throughput. Rejected tasks as Executor already closed and EXECUTor uses limited boundaries for maximum thread and work queue capacity, and when saturated, new tasks submitted in method Execute (java.lang.Runnable) are rejected. In both of these cases, the execute method will call its Rejectedexecutionhandler rejectedexecutionhandler.rejectedexecution ( Java.lang.Runnable, Java.util.concurrent.ThreadPoolExecutor) method. There are four predefined handler policies: In the default ThreadPoolExecutor.AbortPolicy , the handler is rejected and the runtime Rejectedexecutionexception is thrown. In ThreadPoolExecutor.CallerRunsPolicy , the thread invokes the execute itself that runs the task. This strategy provides a simple feedback control mechanism that can slow down the delivery of new tasks. In ThreadPoolExecutor.DiscardPolicy , tasks that cannot be performed are deleted. In ThreadPoolExecutor.DiscardOldestPolicy , if the execution program has not been closed, the task at the head of the work queue will be deleted, and then retry the execution of the program (Repeat this procedure if it fails again).
It is also possible to define and use other kinds of rejectedexecutionhandler classes, but doing so requires great care, especially when the policy is used only for specific capacity or queuing policies.
Example: Click on the Open link
Synchronousqueue
Synchronousqueue is unbounded, a waiting queue without buffering, but because of the nature of the queue itself, you must wait for the other thread to take it after you add the element, and you can think that Synchronousqueue is a blocking queue with a cache value of 1. But the IsEmpty () method always returns the True,remainingcapacity () method always returns the 0,remove () and the RemoveAll () method is always returned by the False,iterator () method always returns empty, peek () method returns null forever.
There are two different ways to declare a synchronousqueue, and they behave differently. The difference between fair and unfair patterns: if the fair mode is adopted: Synchronousqueue will use a fair lock and a FIFO queue to block redundant producers and consumers, thus the system's overall equity strategy , but if the unfair mode (synchronousqueue default): Synchronousqueue the use of unfair locks, while in conjunction with a LIFO queue to manage the surplus producers and consumers, the latter mode, if the producer and consumer processing speed gap, It is easy to be thirsty, that is, there may be some producers or consumers of data will never be processed. Linkedblockingqueue
The Linkedblockingqueue is unbounded and is an unbounded cache waiting queue.
Based on a linked list of blocking queues, a data buffer queue is maintained internally (the queue is composed of linked lists). When the producer puts a data into the queue, the queue takes the data from the producer and caches it inside the queue, and the producer returns immediately; the producer queue is blocked only when the queue buffer reaches the maximum cache capacity (Linkedblockingqueue can specify the value through the constructor). Until consumers consume a single piece of data from the queue, the producer thread wakes up, and the processing of the consumer end is based on the same principle.
Linkedblockingqueue is able to efficiently process concurrent data, and because it uses separate locks for both producer and consumer to control data synchronization, it also means that in high concurrency, producers and consumers can manipulate data in the queue in parallel, In order to improve the concurrency performance of the entire queue. Arraylistblockingqueue
The Arraylistblockingqueue is bounded and is a waiting queue with bounded caches.
An array-based blocking queue, similar to the linkedblockingqueue, that maintains a fixed-length data buffer queue (the queue is composed of arrays). Arrayblockingqueue also holds two reshaping variables that identify the position of the queue's head and tail in the array.
Arrayblockingqueue in the producers to put data and consumers to obtain data, are sharing the same lock object, which means that the two can not really parallel operation, this is particularly different from linkedblockingqueue; According to the principle of implementation, Arrayblockingqueue can be used to completely separate the lock to achieve the full parallel operation of producer and consumer. Doug Lea did not do this, perhaps because the arrayblockingqueue data write and fetch operations are lightweight enough to introduce an independent locking mechanism that does not take up any of the cost of performance in addition to adding additional complexity to the code. Another obvious difference between Arrayblockingqueue and Linkedblockingqueue is that the former does not produce or destroy any additional object instances when inserting or deleting elements, while the latter generates an additional node object. In a system that needs to deal with large quantities of data efficiently and concurrently in a long time, there are some differences in the effect of GC.
Arrayblockingqueue and Linkedblockingqueue are the two most common, most commonly used blocking queues, which generally handle the problem of producer consumers between multithreading, using these two classes enough.