Reprint Please specify source: http://www.cnblogs.com/skywang12345/p/3503458.html
Linkedblockingqueue Introduction
Linkedblockingqueue is a blocking queue implemented by a one-way list. The queue sorts the elements in FIFO (first-in, out-of-order), the new element is inserted at the end of the queue, and the queue get operation obtains the element that is located in the queue header. The throughput of a linked queue is typically higher than an array-based queue, but in most concurrent applications, its predictable performance is low.
In addition, the linkedblockingqueue is optional (prevents excessive bloat), that is, the capacity of the queue can be specified. If not specified, the default capacity size is equal to Integer.max_value.
Linkedblockingqueue principles and data structures
Linkedblockingqueue the data structure, as shown in:
Description :
1. Linkedblockingqueue is inherited from Abstractqueue, which is essentially a FIFO (first-in-one-out) queue.
2. Linkedblockingqueue implements the Blockingqueue interface, which supports multithreading concurrency. When multithreading competes for the same resource, a thread acquires the resource, and other threads need to block the wait.
3. Linkedblockingqueue is achieved through a single-linked list. The
( head) is the table header of the linked list. When the data is taken out, it is inserted from the head of the table header. The
( last) is the footer of the list. When new data is added, it is inserted at the end of the footer. The
( count) is the actual size of the linked list, which is the number of nodes contained in the current list.
( capacity) is the capacity of the list, which is specified when a linked table is created.
( putlock) is an insert lock, Takelock is a lock removed, Notempty is a non-null condition, and Notfull is an "under condition". Concurrency control of the linked list through them.
linkedblockingqueue different locks are used for the insert and remove (delete) operations, respectively, when implementing mutually exclusive access to competing resources for multithreading. For insert operation, synchronize with "Insert lock Putlock", and for take-out operation, synchronize with "Remove Lock Takelock".
Additionally, the insert lock Putlock is associated with "non-full condition notfull", and the Remove lock Takelock and "non-null condition Notempty" are associated. More delicate control locks via notfull and notempty.
--If a thread (thread a) is about to take out the data, the queue is exactly empty, and the thread executes notempty.await () to wait, and when another thread (thread B) inserts data into the queue, it calls Notempty.signal () wake Up " Wait thread on the Notempty ". At this point, thread A will be woken up to continue running. In addition, thread A acquires Takelock before the fetch operation is performed, and then releases Takelock after the fetch operation has been completed. --If the queue is full when a thread (thread h) is about to insert data, the thread will wait for it to execute notfull.await (), and when another thread (thread i) takes out the data, it calls Notfull.signal () to wake up the wait thread on Notfull ”。 At this point, thread H is awakened to continue running. In addition, thread H acquires Putlock before the insert operation, releasing Putlock when the insert operation is complete.
For more information about Reentrantlock and condition, refer to:
Java Multithreading Series--"Juc lock" 02 of mutual exclusion lock Reentrantlock
() Java Multithreading Series--"Juc lock" 03 Fair Lock (One)
Java Multithreading Series--"Juc lock" 04 Fair Lock (II)
Java Multithreading Series--"Juc lock" 05 's Unfair lock
Java Multithreading Series--"Juc lock" 06 of the condition conditions
List of Linkedblockingqueue functions
Create a linkedblockingqueue with a capacity of integer.max_value. Linkedblockingqueue ()//Create a linkedblockingqueue with a capacity of integer.max_value, initially containing the element of the given collection, the element is pressed by that collection The iterator's traversal order is added. Linkedblockingqueue (collection<? extends e> c)//Create a linkedblockingqueue with a given (fixed) capacity. Linkedblockingqueue (int capacity)//completely removes all elements from the queue. void clear ()//removes all available elements from this queue and adds them to the given collection. int Drainto (COLLECTION<? super e> C)//To remove a given number of available elements from this queue and add them to a given Collection. int Drainto (COLLECTION<? super e> C, int maxelements)//Returns an iterator that iterates in the appropriate order on the elements in the queue. Iterator<e> Iterator ()//inserts the specified element at the end of this queue (if it is feasible immediately and does not exceed the capacity of this queue), returns true on success, or False if this queue is full. Boolean offer (E)//inserts the specified element at the end of this queue and, if necessary, waits for a specified time to make the space available. Boolean offer (e E, long timeout, timeunit unit)//Gets the header of this queue without removing it, or null if this queue is empty. E peek ()//Gets and removes the header of this queue and returns null if this queue is empty. E poll ()//Gets and removes the header of this queue, waits for the available elements (if necessary) before the specified wait time. E Poll (long timeout, timeunit unit)//inserts the specified element at the end of this queue and, if necessary, waits for space to become available. void put (e e)//Returns the number of additional elements that this queue can accept and not be blocked, ideally (without memory and resource constraints). int remainingcapacity()//Removes a single instance of the specified element from this queue, if one exists. Boolean remove (Object o)//Returns the number of elements in the queue. int size ()//Gets and removes the head of this queue and waits (if necessary) until the element becomes available. E take ()//Returns an array containing all the elements in this queue in the appropriate order. Object[] ToArray ()//Returns an array containing all the elements in this queue in the appropriate order; The run-time type of the returned array is the run-time type of the specified array. <T> t[] ToArray (t[] a)//returns the string representation of this collection. String toString ()
linkedblockingqueue Source Analysis (jdk1.7.0_40 version)
Linkedblockingqueue.java's complete source code is as follows:
View Code
The following is an analysis of the creation, addition, deletion, and traversal of linkedblockingqueue.
1. Create
The following is illustrated with Linkedblockingqueue (int capacity).
public linkedblockingqueue (int capacity) { if (capacity <= 0) throw new IllegalArgumentException (); This.capacity = capacity; last = head = new node<e> (null);}
Description :
Capacity is the capacity of the "chained blocking queue".
() head and last are the first and last nodes of the "chained blocking queue". Their declarations in the Linkedblockingqueue are as follows:
Capacity private final int capacity;//Current number private final atomicinteger count = new Atomicinteger (0);p rivate transient node< E> Head; The table header of the list is private transient node<e> last; The footer of the list///the "non-null condition" corresponding to the mutex Takelock and the lock that controls the "delete element" Notemptyprivate final Reentrantlock takelock = new Reentrantlock ();p rivate Final Condition notempty = Takelock.newcondition ();//The mutex that controls the "add Element" Putlock and the lock corresponding to the "not full condition" notfullprivate final Reentrantlock Putlock = new Reentrantlock ();p rivate final Condition notfull = Putlock.newcondition ();
The nodes of the linked list are defined as follows:
Static class Node<e> { E item; Data node<e> next; The pointer of the next node , node (E x) {item = x;}}
2. Add
The following is an example of an offer (e E), which describes how to add a linkedblockingqueue.
Public Boolean offer (E e) { if (E = = null) throw new NullPointerException (); If the queue is full, false is returned, indicating that the insert failed. Final Atomicinteger count = This.count; if (count.get () = = capacity) return false; int c =-1; New "Node E" node<e> node = new node (e); Final Reentrantlock putlock = This.putlock; Get "Insert lock Putlock" putlock.lock (); try { //again to "queue is not full" to judge. //If the queue is not full, insert the node. if (Count.get () < capacity) { //Insertion node enqueue (node); Will "number of current nodes" +1 and return "original quantity" c = count.getandincrement (); If the queue is still not full after the element is inserted, the waiting thread on the notfull is awakened. if (c + 1 < capacity) notfull.signal (); } } finally { //release "Insert Lock Putlock" Putlock.unlock (); } If the queue is empty before inserting the node, after inserting the node, wake the waiting thread on the notempty if (c = = 0) signalnotempty (); return c >= 0;}
Description : The Offer () is a simple function of adding element e to the end of the queue.
The source code of Enqueue () is as follows:
private void Enqueue (node<e> Node) { //Assert Putlock.isheldbycurrentthread (); assert last.next = = null; last = Last.next = node;}
The role of Enqueue () is to add node to the end of the queue and set node as the new tail node!
The source code of Signalnotempty () is as follows:
private void Signalnotempty () { final reentrantlock takelock = This.takelock; Takelock.lock (); try { notempty.signal (); } finally { takelock.unlock ();} }
The role of Signalnotempty () is to wake up the waiting thread on the notempty.
3. Remove
The following takes take () as an example, the method of extracting Linkedblockingqueue is described.
Public E take () throws Interruptedexception { e x; int c =-1; Final Atomicinteger count = This.count; Final Reentrantlock takelock = This.takelock; Get "Take out lock", if the current thread is interrupt state, then throw interruptedexception exception takelock.lockinterruptibly (); try { //If queue is empty, wait. while (count.get () = = 0) { notempty.await (); } remove element x = dequeue (); After the element is removed, the number of nodes is 1, and the original number of nodes is returned. C = count.getanddecrement (); if (C > 1) notempty.signal (); } finally { //release "Take Out Lock" takelock.unlock (); } If the queue is full before the element is removed, the waiting thread on the notfull is awakened after the element is fetched. if (c = = capacity) signalnotfull (); return x;}
Description : Take () is the function of taking out and returning the head of the queue. If the queue is empty, wait all the time.
The source code of Dequeue () is as follows:
Private E dequeue () { //Assert Takelock.isheldbycurrentthread (); assert head.item = = null; Node<e> h = head; node<e> first = H.next; H.next = h; Help GC head = first; E x = First.item; First.item = null; return x;}
The function of dequeue () is to delete the head node of the queue and point the table header to the next node of the original head node.
The source code of Signalnotfull () is as follows:
private void Signalnotfull () { final reentrantlock putlock = This.putlock; Putlock.lock (); try { notfull.signal (); } finally { putlock.unlock ();} }
The Signalnotfull () function is to wake the waiting thread on the notfull.
4. Traverse
The following is a description of the Linkedblockingqueue traversal method.
Public iterator<e> Iterator () { return new Itr ();}
Iterator () is actually returning a ITER object.
The ITR class is defined as follows:
Private class Itr implements iterator<e> {//Present node private node<e> current; The last node returned private node<e> Lastret; The value corresponding to the current node is private E currentelement; Itr () {//get "Insert lock Putlock" and "Remove lock Takelock" fullylock (); try {//sets the current element as the next node of the queue header, which is the first active node of the queue, present = Head.next; if (current! = null) currentelement = Current.item; } finally {//release "Insert Lock Putlock" and "Remove lock Takelock" fullyunlock (); }}//returns "whether the next node is null" public boolean Hasnext () {return current! = NULL; } private node<e> NextNode (node<e> p) {for (;;) {node<e> s = p.next; if (s = = p) return head.next; if (s = = NULL | | S.item! = NULL) return s; p = s; }}//Returns the next node public E next () {Fullylock (); try {if (current = = null) throw new Nosuchelementexception (); E x = currentelement; Lastret = current; Current = NextNode (current); Currentelement = (current = = null)? Null:current.item; return x; } finally {Fullyunlock (); }}//delete the next node public void Remove () {if (Lastret = = null) throw new IllegalStateException (); Fullylock (); try {node<e> Node = Lastret; Lastret = null; for (node<e> trail = head, p = trail.next; P! = NULL; Trail = p, p = p.next) {if (P = = node) {unlink (P, trail); Break }}} finally {Fullyunlock (); } }}
Linkedblockingqueue Example
1 Import java.util.*; 2 Import java.util.concurrent.*; 3 4/* 5 * linkedblockingqueue is a "thread-safe" queue, and LinkedList is non-thread-safe. 6 * 7 * Below is an example of "multiple threads working simultaneously and traversing the queue" 8 * (01) The program works correctly when the queue is a Linkedblockingqueue object. 9 * (02) When the queue is a LinkedList object, the program produces an concurrentmodificationexception exception. *11 * @author skywang12 */13 public class LinkedBlockingQueueDemo1 {//Todo:queue is a LinkedList object, the program will error. //private static queue<string> Queue = new linkedlist<string> (), + private static QUEUE<STRING&G T Queue = new linkedblockingqueue<string> (); public static void Main (string[] args) {19 20//Start both The thread is working on the queue! New MyThread ("Ta"). Start (); New MyThread ("TB"). Start ();}24 private static void Printall () {-String value;27 Iterator iter = Queue.iterator (); while (Iter.hasnext ()) {V Alue = (String) iter.next (), System.out.print (value+ ","),}32 SYstem.out.println ();}34 private static Class MyThread extends Thread {MyThread (String name) {37 Super (name),}39 @Override40 public void Run () {$ int i = 0;42 while (i++ < 6) {43//"Thread name" + "-" + "ordinal", String val = Thread.CurrentThread (). GetName () +i;45 Queue.add (val); 46//Traverse the queue through "Iterator". Printall (); 48}49}50}51}
Run results (one time) :
TB1, Ta1, TB1, Ta1, Ta2, TB1, Ta1, Ta2, TA3, TB1, Ta1, Ta2, TA3, TA4, TB1, Ta1, TB1, Ta2, Ta1, TA3, Ta2, TA4, Ta3, Ta5, Ta 4, TB1, Ta5, Ta1, TA6, Ta2, TB1, TA3, Ta1, TA4, Ta2, Ta5, TA3, TA6, TA4, TB2, Ta5, TA6, TB2, TB1, Ta1, Ta2, TA3, TA4, Ta5, TA6, TB2, Tb3, TB1, Ta1, Ta2, TA3, TA4, Ta5, TA6, TB2, Tb3, TB4, TB1, Ta1, Ta2, TA3, TA4, Ta5, TA6, TB2, Tb3, TB4, TB5, t B1, Ta1, Ta2, TA3, TA4, Ta5, TA6, TB2, Tb3, TB4, Tb5, Tb6,
Result Description :
In the sample program, two threads (thread TA and thread TB) are started to operate on Linkedblockingqueue respectively. In the case of thread ta, it takes "thread name" + "ordinal", then adds the string to Linkedblockingqueue, and then traverses and outputs all the elements in the linkedblockingqueue. The thread TB operation is the same as thread ta, except that the name of the thread TB differs from the name of the thread ta.
The program works correctly when the queue is a Linkedblockingqueue object. If you change the queue to LinkedList, the program produces an concurrentmodificationexception exception.
Java and contract--linkedblockqueue