Overview
Blockingqueue as the name implies ' blocked queue ' means that the operations above it are blocked (exceptions to some operations, such as add, etc.). Blockqueue is an important basic tool for the Java.util.concurrent Toolkit and is used in service-side containers such as Threadpoolexcutor and Tomcat.
Classification of Blockingqueue According to the data structure stored by the object
Blockingqueue objects can be stored in: array, linked list, corresponding to the Arrayblockingqueue, Linkedblockingqueu;
Blockingqueue provides a common method of accessing objects
This is illustrated by the implementation code of the Arrayblockingqueue:
Arrayblockingqueue.offer ():
Public Boolean offer (E e) { checknotnull (e); Final Reentrantlock lock = This.lock; Lock.lock (); try { if (count = = Items.length) return false;//returns False if the queue is full, does not throw an exception else { enqueue (e);//Inserts an element into the tail of the queue E return true; } } finally { lock.unlock (); } }
Arrayblockingqueue.offer (timeout) with time-out offer:
Public Boolean offer (e E, long timeout, timeunit unit) throws Interruptedexception { checknotnull (e); Long Nanos = Unit.tonanos (timeout); Final Reentrantlock lock = This.lock; Lock.lockinterruptibly (); During lock lock, the producer thread can be interrupted, what is the benefit? try { while (count = = items.length) { if (Nanos <= 0) return false; Nanos = Notfull.awaitnanos (Nanos); Unlike offer (e), this method waits for the notfull semaphore of the queue, but waits longer than the set timeout. } Enqueue (e); return true; } finally { lock.unlock (); } }
Arrayblockingqueue.add ():
Public boolean Add (E-e) { if (offer (e)) return true; else throw new IllegalStateException ("queue full");//queue filled, throw exception }
Arrayblockingqueue.put ():
public void put (e e) throws interruptedexception { checknotnull (e); Final Reentrantlock lock = This.lock; Lock.lockinterruptibly (); try { while (count = = items.length) notfull.await ();//When the queue is full, the producer thread blocks waiting until the queue is taken by the consumer thread, Notfull Condition is triggered by signal Enqueue (e); } finally { lock.unlock () }}
Java Concurrency Program Foundation--blockingqueue