newScheduledThreadPool延时任务线程池,实现原理

一、Excutors的newScheduleThreadPool程序结构

1、创建延时任务线程池的Excutors源码,ScheduledThreadPoolExecutor实现了ScheduleExecutorService接口

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

2、ScheduledThreadPoolExecutor源码,ScheduledThreadPoolExecutor继承自ThreadPoolExcute类,所以执行super构造方法调用的是ThreadPoolExcute构造函数。

    /**
     * Creates a new ScheduledThreadPoolExecutor with the given core
     * pool size.
     *
     * @param corePoolSize the number of threads to keep in the pool,
     * even if they are idle
     * @throws IllegalArgumentException if <tt>corePoolSize < 0</tt>
     */
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
              new DelayedWorkQueue());
    }

3、我们在构造ThreadPoolExcute时,Queue队列使用了DelayedWorkQueue,这是一个可延时执行阻塞任务的队列,源码如下

    /**
     * An annoying wrapper class to convince javac to use a
     * DelayQueue<RunnableScheduledFuture> as a BlockingQueue<Runnable>
     */
    private static class DelayedWorkQueue
        extends AbstractCollection<Runnable>
        implements BlockingQueue<Runnable> {
        private final DelayQueue<RunnableScheduledFuture> dq = new DelayQueue<RunnableScheduledFuture>();}
我们看到DelayedWordkQueue继承了AbstractCollection接口,实现了BlockingQueue,所以和ArrayBlockingQueue以及LinkedBlockingQueue是兄弟关系。

DelayedWorkQueue定义了一个DelayQueue<RunnableScheduledFuture> dq,所以DelayedWorkQueue的实现是依赖DelayQueue的,


二、关于DelayQueue

    JDK是这样定义的:Delayed元素的一个无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的头部延迟期满后保存时间最长的Delayed元素。如果延迟都还没有期满则队列没有头部,并且poll将返回null。当一个元素的 getDelay(TimeUnit.NANOSECONDS)方法返回一个小于等于0的值时,将发生到期。即使无法使用take或poll移除未到期的元素,也不会将这些元素作为正常元素对待。例如,size方法同时返回到期和未到期元素的计数。此队列不允许使用null元素

可以简单理解他就是一个使用时间作为比较条件的优先级阻塞队列。


1、来看下DelayQUeue源码

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

    private transient final ReentrantLock lock = new ReentrantLock();
    private transient final Condition available = lock.newCondition();
    private final PriorityQueue<E> q = new PriorityQueue<E>();}
2、再来看下他的pool方法和take方法,poll和take都是取元素,并且删除头部元素,区别在于poll()是非阻塞的,如果没有到期的元素则返回null,take()是一直阻塞到返回到期的头部元素。peek():获取但不移除此队列的头部;如果此队列为空,则返回 null。与poll不同,如果队列中没有到期元素可用,则此方法返回下一个将到期的元素(如果存在一个这样的元素)。

    /**
     * Retrieves and removes the head of this queue, or returns <tt>null</tt>
     * if this queue has no elements with an expired delay.
     *
     * @return the head of this queue, or <tt>null</tt> if this
     *         queue has no elements with an expired delay
     */
    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 {
                E x = q.poll();
                assert x != null;
                if (q.size() != 0)
                    available.signalAll();
                return x;
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * Retrieves and removes the head of this queue, waiting if necessary
     * until an element with an expired delay is available on this queue.
     *
     * @return the head of this queue
     * @throws InterruptedException {@inheritDoc}
     */
    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(TimeUnit.NANOSECONDS);
                    if (delay > 0) {
                        long tl = available.awaitNanos(delay);
                    } else {
                        E x = q.poll();
                        assert x != null;
                        if (q.size() != 0)
                            available.signalAll(); // wake up other takers
                        return x;

                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }

3、DelayQueue是怎么实现的:我们知道在使用scheduledThreadPool时,我们给传递了TimeOut和TimeUnit参数作为延时执行时间。 那么DelayQueue是怎么实现的?我们看源码

    /**
     * Retrieves and removes the head of this queue, waiting if necessary
     * until an element with an expired delay is available on this queue,
     * or the specified wait time expires.
     *
     * @return the head of this queue, or <tt>null</tt> if the
     *         specified waiting time elapses before an element with
     *         an expired delay becomes available
     * @throws InterruptedException {@inheritDoc}
     */
    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
                        nanos = available.awaitNanos(nanos);
                } else {
                    long delay = first.getDelay(TimeUnit.NANOSECONDS);
                    if (delay > 0) {
                        if (nanos <= 0)
                            return null;
                        if (delay > nanos)
                            delay = nanos;
                        long timeLeft = available.awaitNanos(delay);
                        nanos -= delay - timeLeft;
                    } else {
                        E x = q.poll();
                        assert x != null;
                        if (q.size() != 0)
                            available.signalAll();
                        return x;
                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }

unit.toNanos(timeout),将时间单位和timeout结合转换成一个纳秒,首先判断peek取出的元素是否为null,如果为null则比较nanos大小,nanos小于0,表示不需要等待,则返回null,如果大于0,则等待nanos单位的时间。如果peek取出的元素不为null,说明头部不为空,再取剩余的延时单位,如果没有延时了,则直接返回q.poll()并且激活其他线程,否则等待nanos单位的时间。


4、有关lock.condition和await()、awaitNanos(long timeout)方法

condition的定义Condition available = lock.newCondition();(newCondition方法是FairSync和NoFairSync类实现的)

awaitNanos造成当前线程在接到信号、被中断或到达指定等待时间之前一直处于等待状态。
与此条件相关的锁以原子方式释放,并且出于线程调度的目的,将禁用当前线程,且在发生以下五种情况之一 以前,当前线程将一直处于休眠状态:

其他某个线程调用此 condition 的 signal() 方法,并且碰巧将当前线程选为被唤醒的线程;或者
其他某个线程调用此 condition 的 signalall() 方法;或者
其他某个线程中断当前线程,且支持中断线程的挂起;或者
已超过指定的等待时间;

await则纯粹是一种和wait差不多的阻塞方法,阻塞当前线程,释放原子锁。



  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值