We continue to discuss the threadpoolexecutor thread pool. In the simplest use of the threadpoolexecutor thread pool, which is given in the previous article, we have adopted only one of the simplest threadpoolexecutor constructors:
Public threadpoolexecutor (int corepoolsize,
int maximumpoolsize,
long KeepAliveTime,
timeunit Unit,
blockingqueue<runnable> Workqueue)
There are actually a number of constructors for the threadpoolexecutor thread pool, one of the most complex of which is:
Public threadpoolexecutor (int corepoolsize,
int maximumpoolsize,
long KeepAliveTime,
timeunit Unit,
blockingqueue<runnable> Workqueue,
Threadfactory threadfactory,
Rejectedexecutionhandler handler)
The Workqueue, threadfactory and handler parameters that we have not described above will be the focus of this article. One: The use of Threadfactory
One of the main tasks of a thread pool is to create a thread if certain conditions are met. In the Threadpoolexecutor thread pool, the work of creating threads is done to threadfactory. To use the thread pool, you must specify Threadfactory.
Similar to the above, if we use a constructor that does not specify the threadfactory used, this time threadpoolexecutor will use a default threadfactory:defaultthreadfactory. (This class is in the Executors tool Class)
Of course, in some special business scenarios, you can also use a custom threadfactory thread factory, the following code fragment:
Import java.util.concurrent.ThreadFactory;
/**
* Test a custom thread factory/public
class Testthreadfactory implements Threadfactory {
@Override
public Thread Newthread (Runnable r) {return
new Thread (R);
}
}
Second: Waiting queues for thread pools
When using the Threadpoolexecutor thread pool, you need to specify a task wait queue that implements the Blockingqueue interface. In the API documentation for the Threadpoolexecutor thread pool, three waiting queues are recommended altogether:synchronousqueue,linkedblockingqueue , and Arrayblockingqueue; queues and Stacks
queues : A special linear structure that allows deletion/read operations at the front end of a linear structure, and allows insertion at the back end of a linear structure, which has a "FIFO" Operating feature:
However, in practical applications, the elements in the queue may not be sorted by "in order of entry". For example, we are going to talk about the Priorityblockingqueue queue.
stacks : Stacks are also a linear structure, but stacks and queues are only allowed to operate at one end of a linear structure, and both the stack and the stack are completed at one end.
2.1 Limited Queues
Synchronousqueue:
"Is such a blocking queue where each put must wait for a take and vice versa." The synchronization queue does not have any internal capacity. This is a blocking queue with no capacity inside, and any element of the insert operation waits for a relative delete/read operation, otherwise the thread that is inserting will wait and vice versa.
synchronousqueue<object> queue = new synchronousqueue<object> ();
Do not use Add because there is no capacity inside this queue, so it throws an exception "IllegalStateException"
//Queue.add (New Object ());
The operation thread is blocked here until another operation thread takes the object
queue.put (New Object ());
Arrayblockingqueue:
A bounded blocking queue supported by the array. This queue sorts the elements according to the FIFO (first-in first out) principle. The new element is inserted at the end of the queue, and the queue fetch operation starts from the queue header to obtain the element. This is a typical "bounded buffer" with fixed-size arrays in which the producer inserts elements and the user extracts the elements. Once you create such a buffer, you can no longer increase its capacity. Attempting to put an element into a full queue causes the operation to be blocked, and attempting to extract elements from an empty queue causes a similar blockage.
We created a arrayblockingqueue and set the queue space to 2
arrayblockingqueue<object> arrayqueue = new Arrayblockingqueue <Object> (2);
Inserts the first object
arrayqueue.put (New Object ());
Inserts a second object,
arrayqueue.put ().
When you insert a third object, the operation thread is blocked.
Arrayqueue.put (New Object ());
Do not use the add operation, as with the Synchronousqueue add operation, they all use the add implementation in Abstractqueue
2.2 Unlimited Queues
Linkedblockingqueue:
Linkedblockingqueue is the waiting queue we use in the Threadpoolexecutor thread pool. It can specify the capacity or not the capacity. Because of its "infinite capacity" feature, I still put it in the category of infinite queues (in fact, any infinite capacity of the queue/stack is a capacity, this capacity is Integer.max_value).
The implementation of the Linkedblockingqueue is based on a linked-list structure, rather than an array like arrayblockingqueue. But in the actual use of the process, do not need to care about its internal implementation, if you specify the size of the linkedblockingqueue, then it reflects the use of characteristics and arrayblockingqueue similar.
linkedblockingqueue<object> linkedqueue = new linkedblockingqueue<object> (2);
Linkedqueue.put (New Object ());
Inserts a second object,
linkedqueue.put ().
When you insert a third object, the operation thread is blocked.
Linkedqueue.put (New Object ());
=======================================
Or the following use:
linkedblockingqueue<object> linkedqueue = new linkedblockingqueue<object> ();
Linkedqueue.put (New Object ());
Inserts a second object,
linkedqueue.put ().
When the nth object is inserted, the
linkedqueue.put (New Object ()) is not blocked;
Linkedblockingdeque
Linkedblockingdeque is a two-terminal queue based on a linked list. The internal structure of the linkedblockingqueue determines that it can only be inserted from the end of the queue, taking elements from the head of the queue, but linkedblockingdeque can insert/remove elements from the tail, and insert elements/remove elements from the head.
linkedblockingdeque<tempobject> linkeddeque = new linkedblockingdeque<tempobject> ();
Push, you can insert element
Linkeddeque.push (new Tempobject (1)) from the head of the queue;
Linkeddeque.push (New Tempobject (2));
Linkeddeque.push (New Tempobject (3));
Poll, you can remove elements from the head of the queue
tempobject tempobject = Linkeddeque.poll ();
Here will print Tempobject.index = 3
System.out.println ("Tempobject.index =" + Tempobject.getindex ());
Put, you can insert element linkeddeque.put from the tail of the queue
(new Tempobject (4));
Linkeddeque.put (New Tempobject (5));
Polllast, the element
Tempobject = Linkeddeque.polllast () can be removed from the tail of the queue.
Here will print Tempobject.index = 5
System.out.println ("Tempobject.index =" + Tempobject.getindex ());
Priorityblockingqueue
The
Priorityblockingqueue is an infinite queue that sorts internal elements by priority. Elements stored in Priorityblockingqueue must implement the comparable interface so that they can be sorted by implementing the CompareTo () method. The highest priority element will always be in the queue's head; Priorityblockingqueue does not guarantee the ordering of the same priority elements, nor does it guarantee that elements other than the highest priority element in the current queue are always in the correct sort position.
What does that mean? Priorityblockingqueue does not guarantee that the ordering of elements other than the head of the queue must be correct. Take a look at the following sample code:
priorityblockingqueue<tempobject> priorityqueue = new priorityblockingqueue<
Tempobject> ();
Priorityqueue.put (New Tempobject (-5));
Priorityqueue.put (New Tempobject (5));
Priorityqueue.put (New Tempobject (-1));
Priorityqueue.put (New Tempobject (1));
The first element is 5//when the Priorityqueue.poll () statement is not actually executed, the second element in the queue is not necessarily 1 tempobject targettempobject = Priorityqueue.poll ();
System.out.println ("Tempobject.index =" + Targettempobject.getindex ());
The second element is 1 targettempobject = Priorityqueue.poll ();
System.out.println ("Tempobject.index =" + Targettempobject.getindex ());
The third element is -1 targettempobject = Priorityqueue.poll ();
System.out.println ("Tempobject.index =" + Targettempobject.getindex ());
The fourth element is -5 targettempobject = Priorityqueue.poll (); System.out.println ("Tempobject.index =" + Targettempobject.getindex ());
This element class must implement the comparable interface
private static class Tempobject implements comparable<tempobject> {
private int index;
public tempobject (int index) {
this.index = index;
}
/**
* @return the index
*
/public int getindex () {return
index;
}
/* (Non-javadoc)
* @see Java.lang.comparable#compareto (java.lang.Object) * * *
@Override
Public int CompareTo (Tempobject o) {return
o.getindex ()-This.index;
}
}
LinkedTransferQueue
LinkedTransferQueue is also an infinite queue, which has a blocking feature in addition to the operational characteristics of the general queue (FIFO): LinkedTransferQueue can be manipulated by a pair of producer/consumer threads, When a consumer inserts a new element into the queue, the consumer thread waits until a consumer thread takes the element away, and vice versa.
The operating characteristics of the linkedtransferqueue can be raised by the following code. In the following code fragment, there are two types of threads: the producer and the consumer, the two threads waiting for each other's actions:
/** * Producer thread/private static class Producerrunnable implements Runnable {private Linkedtransferqueue<tempobjec
T> Linkedqueue;
Public producerrunnable (linkedtransferqueue<tempobject> linkedqueue) {this.linkedqueue = LinkedQueue; @Override public void Run () {for (int index = 1; index++) {try {//to Li Nkedtransferqueue Queue Inserts a new element//Then the producer thread waits until a consumer takes the element out of the queue This.linkedQueue.transfer (n
EW Tempobject (index));
catch (Interruptedexception e) {e.printstacktrace (System.out); /** * Consumer thread/private static class Consumerrunnable implements Runnable {private Linkedtrans
Ferqueue<tempobject> Linkedqueue;
Public consumerrunnable (linkedtransferqueue<tempobject> linkedqueue) {this.linkedqueue = LinkedQueue; @Override public void Run () {Thread CurrentThread =Thread.CurrentThread ();
while (!currentthread.isinterrupted ()) {try {//wait until an element is obtained from the LinkedTransferQueue queue
Tempobject targetobject = This.linkedQueue.take ();
System.out.println ("Thread (" + currentthread.getid () + ") Obtains Targetobject.index =" + Targetobject.getindex ());
catch (Interruptedexception e) {e.printstacktrace (System.out); }
}
}
}
===== The following is the boot code:
linkedtransferqueue<tempobject> linkedqueue = new linkedtransferqueue<tempobject> ();
This is a producer threading thread
Producerthread = new Thread (new Producerrunnable (Linkedqueue));
There are two consumer threads thread
consumerRunnable1 = new Thread (new Consumerrunnable (Linkedqueue));
Thread consumerRunnable2 = new Thread (new Consumerrunnable (Linkedqueue));
Start running
producerthread.start ();
Consumerrunnable1.start ();
Consumerrunnable2.start ();
Here just to main does not exit, there is no demo meaning
Thread currentthread = Thread.CurrentThread ();
Synchronized (CurrentThread) {
currentthread.wait ();
}
Three: Reject Task (handler)
There is also an important interface in the Threadpoolexecutor thread pool: Rejectedexecutionhandler. When a new task submitted to the thread pool cannot be directly processed directly by the "core thread" in the thread pool, the wait queue cannot be joined, a new thread execution cannot be created, or the thread pool has invoked the shutdown () method to stop working, or the thread pool is not in a normal working state When the Threadpoolexecutor thread pool refuses to handle this task, triggering the implementation of the Rejectedexecutionhandler interface defined when creating the Threadpoolexecutor thread pool
When you create the threadpoolexecutor thread pool, you are sure to specify the implementation of the Rejectedexecutionhandler interface. If you call a constructor that does not need to specify the Rejectedexecutionhandler interface, such as:
Public threadpoolexecutor (int corepoolsize,
int maximumpoolsize,
long KeepAliveTime,
timeunit Unit,
blockingqueue<runnable> workqueue)
Public threadpoolexecutor (int corepoolsize,
int maximumpoolsize,
long KeepAliveTime,
timeunit Unit,
blockingqueue<runnable> Workqueue,
Threadfactory threadfactory)
Then the threadpoolexecutor thread pool is created with a default Rejectedexecutionhandler interface implementation, with the source snippet as follows:
public class Threadpoolexecutor extends Abstractexecutorservice {.../** * the default rejected Executi
On handler * * private static final Rejectedexecutionhandler DefaultHandler = new AbortPolicy (); ...//You can see that two constructors in Threadpoolexecutor that do not specify the Rejectedexecutionhandler//interface are all using the default of a Rejectedexecutionhandler interface
Implementation: AbortPolicy public threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, Timeunit, block
Ingqueue<runnable> workqueue) {This (corepoolsize, maximumpoolsize, KeepAliveTime, Unit, Workqueue,
Executors.defaultthreadfactory (), DefaultHandler);
... public threadpoolexecutor (int corepoolsize, int maximumpoolsize,
Long KeepAliveTime, Timeunit unit, Blockingqueue<runnable> Workqueue, Threadfactory threadfact Ory) {This (corepoolsize, maximumpoolsize, KeepAliveTime, Unit, Workqueue, Threadfactory, Defaulthand
LER); }
......
}
In fact, there are four implementations of the Rejectedexecutionhandler interface that can be used directly in threadpoolexecutor :
Callerrunspolicy:
This reject handler will run directly on the task's Run method. Note, however, that you are not running in a thread in the threadpoolexecutor thread pool, but you are directly calling the Run method implemented by this task. The source code is as follows:
public static class Callerrunspolicy implements Rejectedexecutionhandler {
/**
* Creates a {@code Callerrunspolicy}.
* * Public
Callerrunspolicy () {}
/**
* Executes task R in the caller ' s thread, unless the executor
* has b Een shut down, in which case the task is discarded.
*
* @param r The runnable task requested to is executed
* @param e The executor attempting to execute this task< c13/>*/public
void Rejectedexecution (Runnable R, Threadpoolexecutor e) {
if (!e.isshutdown ()) {
R.run ( );
}
}
}
AbortPolicy:
This processor creates a Rejectedexecutionexception exception and throws it when the task is rejected. This process is also the default Rejectedexecutionhandler implementation of the Threadpoolexecutor thread pool.
Discardpolicy:
The Discardpolicy processor silently discards the rejected task, does not throw an exception, does not perform any of the methods of the task in any other way, and does not appear with any log hints.
Discardoldestpolicy:
This processor is very interesting. It checks the waiting queue for the current threadpoolexecutor thread pool. and call the queue's poll () method, forcibly remove the waiting task that is currently in the queue header of the waiting column, and then attempt to submit the currently denied task to the thread pool execution:
public static class Discardoldestpolicy implements Rejectedexecutionhandler {
...
public void Rejectedexecution (Runnable R, Threadpoolexecutor e) {
if (!e.isshutdown ()) {
e.getqueue (). poll (); C6/>e.execute (R);
}
......
}
The
actually looks up the reject processor implementations from these four threadpoolexecutor thread pools, and you can find Callerrunspolicy, Discardpolicy, Discardoldestpolicy processors are not a good way to handle rejected tasks.
Callerrunspolicy The Run method that calls a task directly outside of a thread pool can cause thread-safety problems; Discardpolicy silently ignores rejected tasks, and there is no output log or prompt, Developers do not know that the thread pool process has been incorrectly handled, E.getqueue () in Discardoldestpolicy (). Poll () seems to be scientific, but if there is a capacity problem waiting for the queue, in most cases the code for this thread pool appears to be a bug. The most scientific or abortpolicy way to do this is to throw an exception, which is handled by developers.