Java DelayQueue包装类

public class DelayQueueWrapper<T> {



    private TimeUnit timeUnit;

    private final Long capacity;

    private long currentSize;

    private DelayQueue<DelayQueueTarget<T>> delayQueue;

    public DelayQueueWrapper(long capacity, TimeUnit timeUnit) {
        this.delayQueue = new DelayQueue<>();
        this.capacity = capacity;
        this.currentSize = 0;
    }


    /**
     * offer element
     * @param t
     * @param delay
     * @return
     */
    public synchronized boolean offer(T t, long delay) {
        if (this.currentSize > capacity) {
            return false;
        }

        this.delayQueue.add(new DelayQueueTarget<T>(t, timeUnit.toMillis(delay)));

        this.currentSize++;

        return true;
    }


    /**
     * peek element
     * @return
     */
    public synchronized T peek(){
        if (this.currentSize < 0) {
            return null;
        }

        T t = Optional.ofNullable(this.delayQueue.peek())
                .map(DelayQueueTarget::getData)
                .orElse(null);
        this.currentSize--;
        return t;

    }





    public static class DelayQueueTarget<T> implements Delayed{

        private T data;
        private long startTime;

        public DelayQueueTarget(T data, long delayInMilliseconds) {
            this.data = data;
            this.startTime = System.currentTimeMillis() + delayInMilliseconds;
        }


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

        @Override
        public int compareTo(Delayed o) {
            return Ints.saturatedCast(
                    this.startTime - ((DelayQueueTarget<?>) o).startTime);
        }


        public T getData() {
            return data;
        }
    }





}

posted on 2023-02-20 17:27  mindSucker  阅读(9)  评论(0编辑  收藏  举报