java-延时队列-DelayQueue源码分析

首先延时队列的发现是基于一个实际场景:如何处理超时的订单

这个问题很容易想到解决方案

(1)写一个定时任务,轮询超时的订单(缺点:性能消耗过大,对数据库造成压力)

(2)放入延时队列当中

那么我就选择一下延时队列,看一下java的实现吧。

贴出一个入门的博客:https://www.cnblogs.com/barrywxx/p/8525907.html

然后我们就以这个博客来入手源码

1.首先看下如何使用

public static void main(String[] args) {    
            // 创建延时队列    
            DelayQueue<Message> queue = new DelayQueue<Message>();    
            // 添加延时消息,m1 延时3s    
            Message m1 = new Message(1, "world", 3000);    
            // 添加延时消息,m2 延时10s    
            Message m2 = new Message(2, "hello", 10000);    
            //将延时消息放到延时队列中  
            queue.offer(m2);    
            queue.offer(m1);    
            // 启动消费线程 消费添加到延时队列中的消息,前提是任务到了延期时间   
            ExecutorService exec = Executors.newFixedThreadPool(1);  
            exec.execute(new Consumer(queue));  
            exec.shutdown();  
}
public class Consumer implements Runnable {  
    // 延时队列 ,消费者从其中获取消息进行消费  
    private DelayQueue<Message> queue;  
  
    public Consumer(DelayQueue<Message> queue) {  
        this.queue = queue;  
    }  
  
    @Override  
    public void run() {  
        while (true) {  
            try {  
                Message take = queue.take();  
                System.out.println("消费消息id:" + take.getId() + " 消息体:" + take.getBody());  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}

那么从上面可以看得出来,最基础的两个方法便是queue.offer(X),queue.take();

1.那么就从offer()开始看起

public boolean offer(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            //这里DelayQueue其实内置了一个队列,大部分功能是沿用了优先级队列
            //优先级队列大致就是讲的是 1 2 3 4 5 6 7这7个数你随便指定先后顺序放入
            //都只会有一种结果
            //private final PriorityQueue<E> q = new PriorityQueue<E>();
            q.offer(e);
            //如果e是队首的话就唤醒其余等待线程
            if (q.peek() == e) {
                leader = null;
                available.signal();
            }
            return true;
        } finally {
            lock.unlock();
        }
}
//接着看q.offer(e);
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);
}
//一个一个的对比,一般来说是自己实现compareTo的实现
//一般就是对比时间
private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (comparator.compare(x, (E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
}

2.take()

public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            for (;;) {
                //peek(): return (size == 0) ? null : (E) queue[0];
                //就是获取第一个元素
                E first = q.peek();
                if (first == null)
                    //availabe是一个condition
                    available.await();
                else {
                    //对比当前时间是否达到
                    long delay = first.getDelay(NANOSECONDS);
                    //已经到了
                    if (delay <= 0)
                        //返回头结点,并将其移除
                        return q.poll();
                    first = null; // don't retain ref while waiting
                    //leader是用来提高效率的
                    //因为前面是lock.lockInterruptibly(),
                    //可能存在多个线程一起去take()
                    //所以避开过多线程一起操作
                    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();
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值