Java. util. concurrent package source code reading 20 DelayQueue, java. util package

Source: Internet
Author: User
Tags comparable

Java. util. concurrent package source code reading 20 DelayQueue, java. util package

DelayQueue stores Delayed objects or child objects in an orderly manner. If an element is not removed from the queue, the object is returned only after the delay is exhausted.

The so-called Delayed type inherits the Comparable interface because it needs to be compared:

public interface Delayed extends Comparable<Delayed> {    long getDelay(TimeUnit unit);}

In fact, the sort and delay of Delayed objects are irrelevant, because the Comparable compare method is implemented by the user. DelayQueue only ensures that the delay of the returned object is exhausted.

 

DelayQueue needs to sort and store Delayed objects with blocking function at the same time, but the blocking process is accompanied by blocking of the Delayed wait type. Therefore, BlockingPriorityQueue cannot be used directly, instead, we use a non-blocking version of PriorityQueue for sorting and storage.

private final PriorityQueue<E> q = new PriorityQueue<E>();

 

Therefore, DelayQueue needs to implement its own blocking function (requires a Condition ):

private final Condition available = lock.newCondition();

 

The old rule is to look at the offer method first:

Public boolean offer (E e) {final ReentrantLock lock = this. lock; lock. lock (); try {q. offer (e); // if the original queue is empty, reset the leader thread and notify the available condition if (q. peek () = e) {leader = null; available. signal () ;}return true ;}finally {lock. unlock ();}}

By the way, because DelayQueue does not limit the length, adding elements does not cause blocking because the queue is full. Therefore, the timeout setting of the offer method with timeout does not work:

Public boolean offer (E e, long timeout, TimeUnit unit) {// return offer (e );}

 

Because DelayQueue needs to implement blocking by itself, the focus should be on two blocking methods: the take method without timeout and the poll method with timeout.

The common poll method is very simple. If the delay time is not exhausted, return null directly.

    public E poll() {        final ReentrantLock lock = this.lock;        lock.lock();        try {            E first = q.peek();            if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)                return null;            else                return q.poll();        } finally {            lock.unlock();        }    }

 

Next, let's look at the take and poll methods with timeout. After reading DelayedWorkQueue, this part is better understood:

Public E take () throws InterruptedException {final ReentrantLock = this. lock; lock. lockInterruptibly (); try {for (;) {// If the queue is empty, wait until the available condition is notified E first = q. peek (); if (first = null) available. await (); else {long delay = first. getDelay (TimeUnit. NANOSECONDS); // if the delay time is reached, return the first element if (delay <= 0) return q. poll (); // the existence of the leader thread indicates that other threads are waiting, so the current thread must wait for else if (leader! = Null) available. await (); else {Thread thisThread = Thread. currentThread (); leader = thisThread; // if there is no leader thread, set the current thread to the leader thread // try to wait until the delay time is exhausted (may be returned in advance, so the next // loop will continue to process) try {available. awaitNanos (delay);} finally {// if the leader thread is still the current thread, reset it for the next loop. // When waiting for the available condition, the lock may be occupied by other threads, causing the // leader thread to be changed. Therefore, check if (leader = thisThread) leader = null ;}}}} finally {// if no other thread is waiting and the queue is not empty, notify the available condition if (leader = null & q. peek ()! = Null) available. signal (); lock. unlock ();}}

Let's take a look at the poll method with timeout, which is very similar to DelayedWorkQueue:

Public E poll (long timeout, TimeUnit unit) throws InterruptedException {long nanos = unit. toNanos (timeout); final ReentrantLock lock = this. lock; lock. lockInterruptibly (); try {for (;) {E first = q. peek (); if (first = null) {if (nanos <= 0) return null; else // try to wait for the available condition and record the remaining time nanos = available. awaitNanos (nanos);} else {long delay = first. getDelay (TimeUnit. NANOSECONDS); if (delay <= 0) return q. poll (); if (nanos <= 0) return null; // when the leader thread is not empty (delay> = nanos ), the waiting time // It seems that delay is more reasonable, but nanos is also acceptable, because the available condition will be awakened when other threads return in front of the current thread, // It is easier to use nanos and nonas <delay to merge if (nanos <delay | leader! = Null) nanos = available. awaitNanos (nanos); else {Thread thisThread = Thread. currentThread (); leader = thisThread; try {long timeLeft = available. awaitNanos (delay); // nanos needs to be updated to nanos-= delay-timeLeft;} finally {if (leader = thisThread) leader = null ;}}}}} finally {if (leader = null & q. peek ()! = Null) available. signal (); lock. unlock ();}}

 

We have understood DelayedWorkQueue before. It is very easy to understand DelayQueue.

 




Related Article

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.