内存延迟队列实现DelayQueue

jdk 提供了延迟队列:java.util.concurrent.DelayQueue

我们基于 DelayQueue 实现一个固定时间的延迟队列

下面是固定延迟时间的装饰类实现,demo 在下面的main方法中

/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2017 All Rights Reserved.
 */
package com.bestpay.messagecenter.push.common.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author lxn
 * @version Id: DelayedWrapper.java, v 0.1 2017/7/14 22:10 lxn Exp $$
 */
@Slf4j
public class DelayedWrapper implements Delayed {

    private long deadline;
    private T bean;

    public DelayedWrapper(T bean,long delayTime,TimeUnit delayTimeUnit){
        this.deadline=System.currentTimeMillis()+TimeUnit.MILLISECONDS.convert(delayTime,delayTimeUnit);
        this.bean=bean;
    }



    @Override
    public long getDelay(TimeUnit unit) {
        long delay=  unit.convert(deadline-System.currentTimeMillis(),TimeUnit.MILLISECONDS);
        return delay;
    }



    @Override
    public int compareTo(Delayed o) {
        long diff;
        if(o instanceof DelayedWrapper){
            diff = this.deadline-((DelayedWrapper) o).getDeadline();
        }else {
            diff = this.getDelay(TimeUnit.MILLISECONDS)-o.getDelay(TimeUnit.MILLISECONDS);
        }
        return (diff == 0) ? 0 : ((diff < 0) ? -1 : 1);
    }

    public T get(){
        return bean;
    }

    /**
     * 获取 deadline
     *
     * @return deadline
     */
    public long getDeadline() {
        return deadline;
    }

    @Override
    public String toString() {
        return "DelayedWrapper{" +
                "deadline=" + deadline +
                ", bean=" + bean +
                '}';
    }

    public static void main(String[] args) {

        try {
            DelayQueue> queue =new DelayQueue<>();

            for(int i=0;i<100000;i++) {
                queue.add(new DelayedWrapper(i, i, TimeUnit.SECONDS));
            }
            for(int i=0;i<100000;i++) {
                log.info(String.valueOf(queue.take()));
            }
        }catch (Exception e){
            log.error("DelayedWrapper Exception:{}", e);
        }

    }
}

你可能感兴趣的:(java,软件工程)