Blocking queue, blocking queue java
1. Principle of blocking queues
The difference between a blocking queue and a common queue is that when the blocking queue is empty, the operations to obtain elements from the queue will be blocked. When the queue is full, adding elements to a queue is blocked.
The thread that tries to obtain elements from an empty blocking queue will be blocked until other threads Insert new elements into the empty queue. Similarly, threads trying to add new elements to a full blocking queue will also be blocked until other threads make the queue idle again.
2. Simple implementation of blocking queues
/*** A blocking queue implemented based on the linked list ** @ author jade **/public class BlockingQueue {private int capacity; // blocking queue capacity private List queue = new blocked List (); // a blocking queue public BlockingQueue () {this (Integer. MAX_VALUE);} public BlockingQueue (int capacity) {this. capacity = capacity;}/*** incoming queue *** @ param item * @ throws InterruptedException */public synchronized void enqueue (Object item) throws InterruptedException {while (this. queue. size () = this. capacity) {wait ();} if (this. queue. size () = 0) {policyall ();} this. queue. add (item);}/*** output queue ** @ return * @ throws InterruptedException */public synchronized Object dequeue () throws InterruptedException {while (this. queue. size () = 0) {wait ();} if (this. queue. size () = this. capacity) {policyall ();} return this. queue. remove (0 );}}Note:
1) In the enqueue and dequeue methods, the notifyAll method is called only when the queue size is equal to the upper limit (capacity) or lower limit (0.
If the queue size is neither equal to nor equal to the upper limit, no thread will be blocked when calling the enqueue or dequeue method, so you do not need to wake up, can normally add or remove elements to or from the queue.
2) The enqueue and dequeue methods both use synchronized to obtain the lock when entering synchronized and release the lock when exiting. If synchronized is not available, the lock cannot be determined when wait/notify is used directly.
3. Define blockingqueue
In java. util. the concurrent package provides several blocking queues. The blocked blockingqueue is a blocking Queue Based on the linked list. If you do not specify the capacity when creating the blocked blockingqueue object, the default size is Integer. MAX_VALUE.
First, let's take a look at several member variables in the javasblockingqueue class:
private static final long serialVersionUID = -6903933977591709194L; private final int capacity; private final AtomicInteger count = new AtomicInteger(); transient Node<E> head; private transient Node<E> last; private final ReentrantLock takeLock = new ReentrantLock(); private final Condition notEmpty = this.takeLock.newCondition(); private final ReentrantLock putLock = new ReentrantLock(); private final Condition notFull = this.putLock.newCondition();
It can be seen that the element stored in the queue blockingqueue is actually a linked list. head and last represent the head node and the next node of the linked list respectively, and capacity indicates the capacity of the queue.
Takelock, putLock is reentrant lock, notEmpty and notFull are waiting conditions.
Let's take a look at the constructor of LinkedBlockingQueue. The constructor has three overloaded versions:
public LinkedBlockingQueue() { this(Integer.MAX_VALUE); } public LinkedBlockingQueue(int paramInt) { if (paramInt <= 0) { throw new IllegalArgumentException(); } this.capacity = paramInt; this.last = (this.head = new Node(null)); } public LinkedBlockingQueue(Collection<? extends E> paramCollection) { this(Integer.MAX_VALUE); ReentrantLock localReentrantLock = this.putLock; localReentrantLock.lock(); try { int i = 0; Iterator localIterator = paramCollection.iterator(); while (localIterator.hasNext()) { Object localObject1 = localIterator.next(); if (localObject1 == null) { throw new NullPointerException(); } if (i == this.capacity) { throw new IllegalStateException("Queue full"); } enqueue(new Node(localObject1)); i++; } this.count.set(i); } finally { localReentrantLock.unlock(); } }
The default capacity of the first constructor is Integer. MAX_VALUE. The second constructor only has one parameter to specify the capacity. The third constructor can specify a set for initialization.
Then let's look at the implementation of the two key methods: put () and take ():
Public void put (E paramE) throws InterruptedException {
// Ensure that the put element is non-empty if (paramE = null) {throw new NullPointerException ();} int I =-1; Node localNode = new Node (paramE ); reentrantLock localReentrantLock = this. putLock; AtomicInteger localAtomicInteger = this. count;
// Response interrupt localReentrantLock. lockInterruptibly (); try {
While (localAtomicInteger. get () = this. capacity) {this. notFull. await (); // blocking} enqueue (localNode); I = localAtomicInteger. getAndIncrement (); if (I + 1 <this. capacity) {this. notFull. signal (); // use signal () to improve performance, and wake up the blocked threads in the notFull condition queue during put. } Finally {localReentrantLock. unlock () ;}if (I = 0) {signalNotEmpty (); // put, when I = 0, it will wake up the blocked threads in the notEmpty condition queue, but this requires the takeLock lock.
}
}
public E take() throws InterruptedException { int i = -1; AtomicInteger localAtomicInteger = this.count; ReentrantLock localReentrantLock = this.takeLock; localReentrantLock.lockInterruptibly(); Object localObject1; try { while (localAtomicInteger.get() == 0) { this.notEmpty.await(); } localObject1 = dequeue(); i = localAtomicInteger.getAndDecrement(); if (i > 1) { this.notEmpty.signal(); } } finally { localReentrantLock.unlock(); } if (i == this.capacity) { signalNotFull(); } return (E)localObject1; }
Similar to the put method, the put method only waits for the notFull signal, while the take method waits for the notEmpty signal.
LinkedBlockingQueue maintains a Data Buffer Queue (which consists of a linked list). When a producer puts data into the queue, the queue obtains data from the producer, and cached in the queue, and the Producer returns immediately. The producer queue is blocked only when the queue buffer reaches the maximum cache capacity (blockingqueue can be specified by the constructor, until the consumer consumes a copy of data from the queue, the producer thread will be awakened, and the processing of the consumer is based on the same principle.
The reason why LinkedBlockingQueue can efficiently process concurrent data is that it also uses independent locks for the producer end and consumer end to control data synchronization, this also means that in the case of high concurrency, producers and consumers can operate data in the queue in parallel to improve the concurrency performance of the entire queue.
LinkedBlockingQueue uses ReentrantLock internally to implement putLock and takeLock ). The condition variable on putLock is notFull, which can be used to wake up the thread blocking on putLock. The condition variable on takeLock is notEmtpy. You can use notEmpty to wake up the thread blocking on takeLock.
Refer to the following blog:
Http://www.cnblogs.com/moonandstar08/p/4893337.html
Http://www.cnblogs.com/dolphin0520/p/3932906.html