Java Blockingqueue Source Code Analysis

Source: Internet
Author: User

Brief introduction

Blockingqueue is a multithreaded secure blocking queue provided by the Java concurrent package with subclasses including Linkedblockingqueue and Arrayblockingqueue.

Key API

When it comes to queues, there are several insertions and deletions in the Blockingqueue API.
These methods take different actions when encountering an unsatisfied execution condition, such as when the queue is full (when the element is added)/the queue is empty (when the element is taken): Throws an exception, returns FALSE/NULL, blocks the thread that invokes the API, waits for a certain amount of time, and so on. Specifically, the following table:

Throws exception Special value Blocks Times out
Insert Add (E) Offer (e) Put (e) Offer (E,time,unit)
Remove Remove () Poll () Take () Poll (Time,unit)
Examine Element () Peek () Not applicable Not applicable
Arrayblockingqueue

Arrayblockingqueue is an array-based blocking queue that, when creating a arrayblockingqueue, needs to provide a parameter that represents the size of the queue.

Arrayblockingqueue is thread-safe, but how does it work? This requires a note of the three properties in the class:

    /** Main lock guarding all access */    final ReentrantLock lock;    /** Condition for waiting takes */    privatefinal Condition notEmpty;    /** Condition for waiting puts */    privatefinal Condition notFull;

Here a lock, two condition variables, manages the mutex and synchronization of all threads that use the API. The specific lock and condition variables of the theoretical knowledge, can be found in the relevant operating system books.

Offer vs put
     Public Boolean  Offer(e) {Checknotnull (e);FinalReentrantlock lock = This. Lock; Lock.lock ();Try{if(count = = items.length)return false;Else{Insert (E);return true; }        }finally{Lock.unlock (); }    } Public void put(e)throwsinterruptedexception {checknotnull (e);FinalReentrantlock lock = This. Lock; Lock.lockinterruptibly ();Try{ while(count = = items.length) notfull.await ();        Insert (e); }finally{Lock.unlock (); }    }

As can be seen, two methods in the queue to add elements, is the first lock on the critical section, the difference is that the offer method if the detection of the queue is full, will be directly returned to the False;put method, if the detection of the queue is full, the thread will be blocked in the notfull condition variable, so that the thread will release the lock, Let other threads enter the critical section. At a later time, a thread pulls an element out of the queue, the queue is no longer empty, and the thread wakes up a thread that is blocked on the notfull condition variable, and the Put method is possible to complete.

Poll vs Take
publictakethrows InterruptedException {        finalthis.lock;        lock.lockInterruptibly();        try {            while0)                notEmpty.await();            return extract();        finally {            lock.unlock();        }    }

Take is the same logic as put, except this time if the queue is empty, the thread blocks on the notempty condition variable, waits for other threads to add elements to the queue, and wakes up the blocked thread on Notempty.

   publicpoll() {        finalthis.lock;        lock.lock();        try {            return0null : extract();        finally {            lock.unlock();        }    }

The poll method returns null directly when the queue is detected as empty, otherwise the team head element is removed.

       PublicEPoll(LongTimeout, timeunit unit)throwsinterruptedexception {LongNanos = Unit.tonanos (timeout);FinalReentrantlock lock = This. Lock; Lock.lockinterruptibly ();Try{ while(Count = =0) {if(Nanos <=0)return NULL;            Nanos = Notempty.awaitnanos (Nanos); }returnExtract (); }finally{Lock.unlock (); }    }

Poll also has a more interesting overload implementation, which takes advantage of the condition variable's timer method Awaitnanos. The time size is converted to the number of nanoseconds based on the time unit, and when the queue capacity is 0, the Condition.awaitnanos (...) is used, the timing is timed, and Null is returned after the timeout.

Java Blockingqueue Source Code Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.