当前位置: 主页 > JAVA语言

java 延迟队列-队列java实现

发布时间:2023-02-09 22:16   浏览次数:次   作者:佚名

DelayQueue是一个延迟队列,可以在指定时间后执行。 它的底层使用PriorityQueue作为底层数据结构。

在解释DelayQueue之前java 延迟队列,我们需要先解释一下PriorityQueue。

PriorityQueue是一个优先级队列,底层使用一个可动态扩展的数组作为基本数据结构,实现了堆结构。 默认是一个小的顶层堆。

public class PriorityQueue<E> extends AbstractQueue<E>
    implements java.io.Serializable {
   /**
     * Priority queue represented as a balanced binary heap: the two
     * children of queue[n] are queue[2*n+1] and queue[2*(n+1)].  The
     * priority queue is ordered by comparator, or by the elements'
     * natural ordering, if comparator is null: For each node n in the
     * heap and each descendant d of n, n <= d.  The element with the
     * lowest value is in queue[0], assuming the queue is nonempty.
     */
    transient Object[] queue; // non-private to simplify nested class access
    /**
     * The number of elements in the priority queue.
     */
    private int size = 0;
	
}

我们主要看它的入队和出队操作:

 public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }
private void siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }
private void siftUpComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }
public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        E result = (E) queue[0];
        E x = (E) queue[s];
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        return result;
    }
private void siftDown(int k, E x) {
        if (comparator != null)
            siftDownUsingComparator(k, x);
        else
            siftDownComparable(k, x);
    }
private void siftDownComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>)x;
        int half = size >>> 1;        // loop while a non-leaf
        while (k < half) {
            int child = (k << 1) + 1; // assume left child is least
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
                c = queue[child = right];
            if (key.compareTo((E) c) <= 0)
                break;
            queue[k] = c;
            k = child;
        }
        queue[k] = key;
    }

延迟队列

DelayQueue的类声明结构如下


public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
    implements BlockingQueue<E> {
}

表名操作的元素必须是一个实现了Delayed接口的类,声明如下:

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

如您所见java 延迟队列,实现此接口也必须实现 Comparable 接口。

我们来看看DelayQueue的dequeue和enqueue方法:


private final Condition available = lock.newCondition();
public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            for (;;) {
                E first = q.peek();
                if (first == null)
                    available.await();
                else {
                    long delay = first.getDelay(NANOSECONDS);
                    if (delay <= 0)
                        return q.poll();
                    first = null; // don't retain ref while waiting
                    if (leader != null)
                        available.await();
                    else {
                        Thread thisThread = Thread.currentThread();
                        leader = thisThread;
                        try {
                            available.awaitNanos(delay);
                        } finally {
                            if (leader == thisThread)
                                leader = null;
                        }
                    }
                }
            }
        } finally {
            if (leader == null && q.peek() != null)
                available.signal();
            lock.unlock();
        }
    }
    public boolean offer(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            q.offer(e);
            if (q.peek() == e) {
                leader = null;
                available.signal();
            }
            return true;
        } finally {
            lock.unlock();
        }
    }

DelayQueue内部只有一把锁和一个条件等待锁。

从队列中获取数据时,先从PriorityQueue队列中获取一个元素,如果该元素已经过期,则直接返回该元素,如果该元素还没有过期, 1.当leader线程不为空​​时(此时leader线程获取了一个未过期的元素,但leader线程只是阻塞等待,直到元素过期,过期后才会被唤醒),则当前线程阻塞等待,如果leader为空,则当前没有线程获取表名,则当前线程先获取。

可以看出,DelayQueue中并不是每个线程都一直等待,而是在线程获取到元素后(此时已经获取到锁),如果元素需要一定时间过期,那么只让当前线程等待for a fixed time will 唤醒当前线程,避免线程等待