32-DelayQueue

精巧好用之DelayQueue

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>();  
}

内部结构非常简单,一把锁,一个条件,一个优先级队列。

DelayQueue要求放入其中的元素必须实现Delayed接口,看下这个接口:

/** 
 * A mix-in style interface for marking objects that should be 
 * acted upon after a given delay. 
 * 
 * <p>An implementation of this interface must define a 
 * <tt>compareTo</tt> method that provides an ordering consistent with 
 * its <tt>getDelay</tt> method. 
 * 
 * @since 1.5 
 * @author Doug Lea 
 */  
public interface Delayed extends Comparable<Delayed> {  
    /** 
     * Returns the remaining delay associated with this object, in the 
     * given time unit. 
     * 
     * @param unit the time unit 
     * @return the remaining delay; zero or negative values indicate 
     * that the delay has already elapsed 
     */  
    long getDelay(TimeUnit unit);  
}  

这个接口定义了一个返回延时值的方法,而且扩展了Comparable接口,具体实现的排序方式会和延时值有关,延时值最小的会排在前面。再结合上面DelayQueue的内部数据结构,我们就可以大概脑补这个过程了。

既然是阻塞队列,还是从put和take方法开始入手,先看下put方法:

public boolean offer(E e) {  
    final ReentrantLock lock = this.lock;  
    lock.lock();  
    try {  
        //获取队头元素。  
        E first = q.peek();  
        //将元素放入内部队列。  
        q.offer(e);  
        if (first == null || e.compareTo(first) < 0)  
            available.signalAll(); //如果队头没有元素 或者 当前元素比队头元素的延时值小,那么唤醒available条件上的线程。  
        return true;  
    } finally {  
        lock.unlock();  
    }  
}  
/** 
 * 插入一个元素到延迟队列,由于队列是无界的,所以这个方法永远不会阻塞。 
 * 
 * @param e the element to add 
 * @throws NullPointerException {@inheritDoc} 
 */  
public void put(E e) {  
    offer(e);  
}  

再看下take方法:

public E take() throws InterruptedException {  
    final ReentrantLock lock = this.lock;  
    lock.lockInterruptibly();  
    try {  
        for (;;) {  
            //获取队头元素。  
            E first = q.peek();  
            if (first == null) {  
                available.await();//如果队头没有元素,那么当前线程在available条件上等待。  
            } else {  
                //如果队头有元素,获取元素的延时值。  
                long delay =  first.getDelay(TimeUnit.NANOSECONDS);  
                if (delay > 0) {  
                    //如果延时值大于0,那么等待一下。  
                    long tl = available.awaitNanos(delay);   
                } else {  
                    //否则获取并移除队列列头元素。  
                    E x = q.poll();  
                    assert x != null;  
                    if (q.size() != 0)  
                        available.signalAll(); // 如果内部队列中还有元素,那么唤醒其他在available条件上等待着的take线程。  
                    return x;  
                }  
            }  
        }  
    } finally {  
        lock.unlock();  
    }  
}  

使用场景

我们谈一下实际的场景吧。我们在开发中,有如下场景:

a) 关闭空闲连接。服务器中,有很多客户端的连接,空闲一段时间之后需要关闭之。

b) 缓存。缓存中的对象,超过了空闲时间,需要从缓存中移出。

c) 任务超时处理。在网络协议滑动窗口请求应答式交互时,处理超时未响应的请求。

一种笨笨的办法就是,使用一个后台线程,遍历所有对象,挨个检查。这种笨笨的办法简单好用,但是对象数量过多时,可能存在性能问题,检查间隔时间不好设置,间隔时间过大,影响精确度,过小则存在效率问题。而且做不到按超时的时间顺序处理。

这场景,使用DelayQueue最适合了。

以下是一个缓存的简单实现。共包括三个类Pair、DelayItem、Cache。如下:

public class Pair<K, V> {
    public K first;

    public V second;

    public Pair() {}

    public Pair(K first, V second) {
        this.first = first;
        this.second = second;
    }
}

以下是Delayed的实现:

public class DelayItem<T> implements Delayed {
    /** Base of nanosecond timings, to avoid wrapping */
    private static final long NANO_ORIGIN = System.nanoTime();

    /**
     * Returns nanosecond time offset by origin
     */
    final static long now() {
        return System.nanoTime() - NANO_ORIGIN;
    }

    /**
     * Sequence number to break scheduling ties, and in turn to guarantee FIFO order among tied
     * entries.
     */
    private static final AtomicLong sequencer = new AtomicLong(0);

    /** Sequence number to break ties FIFO */
    private final long sequenceNumber;

    /** The time the task is enabled to execute in nanoTime units */
    private final long time;

    private final T item;

    public DelayItem(T submit, long timeout) {
        this.time = now() + timeout;
        this.item = submit;
        this.sequenceNumber = sequencer.getAndIncrement();
    }

    public T getItem() {
        return this.item;
    }

    public long getDelay(TimeUnit unit) {
        long d = unit.convert(time - now(), TimeUnit.NANOSECONDS);
        return d;
    }

    public int compareTo(Delayed other) {
        if (other == this) // compare zero ONLY if same object
            return 0;
        if (other instanceof DelayItem) {
            DelayItem x = (DelayItem) other;
            long diff = time - x.time;
            if (diff < 0)
                return -1;
            else if (diff > 0)
                return 1;
            else if (sequenceNumber < x.sequenceNumber)
                return -1;
            else
                return 1;
        }
        long d = (getDelay(TimeUnit.NANOSECONDS) - other.getDelay(TimeUnit.NANOSECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }
}

以下是Cache的实现,包括了put和get方法,还包括了可执行的main函数。

public class Cache<K, V> {
    private static final Logger LOG = Logger.getLogger(Cache.class.getName());

    private ConcurrentMap<K, V> cacheObjMap = new ConcurrentHashMap<K, V>();

    private DelayQueue<DelayItem<Pair<K, V>>> q = new DelayQueue<DelayItem<Pair<K, V>>>();

    private Thread daemonThread;

    public Cache() {

        Runnable daemonTask = new Runnable() {
            public void run() {
                daemonCheck();
            }
        };

        daemonThread = new Thread(daemonTask);
        daemonThread.setDaemon(true);
        daemonThread.setName("Cache Daemon");
        daemonThread.start();
    }

    private void daemonCheck() {

        if (LOG.isLoggable(Level.INFO))
            LOG.info("cache service started.");

        for (;;) {
            try {
                DelayItem<Pair<K, V>> delayItem = q.take();
                if (delayItem != null) {
                    // 超时对象处理
                    Pair<K, V> pair = delayItem.getItem();
                    cacheObjMap.remove(pair.first, pair.second); // compare and remove
                }
            } catch (InterruptedException e) {
                if (LOG.isLoggable(Level.SEVERE))
                    LOG.log(Level.SEVERE, e.getMessage(), e);
                break;
            }
        }

        if (LOG.isLoggable(Level.INFO))
            LOG.info("cache service stopped.");
    }

    // 添加缓存对象
    public void put(K key, V value, long time, TimeUnit unit) {
        V oldValue = cacheObjMap.put(key, value);
        if (oldValue != null)
            q.remove(key);

        long nanoTime = TimeUnit.NANOSECONDS.convert(time, unit);
        q.put(new DelayItem<Pair<K, V>>(new Pair<K, V>(key, value), nanoTime));
    }

    public V get(K key) {
        return cacheObjMap.get(key);
    }

    // 测试入口函数
    public static void main(String[] args) throws Exception {
        Cache<Integer, String> cache = new Cache<Integer, String>();
        cache.put(1, "aaaa", 3, TimeUnit.SECONDS);

        Thread.sleep(1000 * 2);
        {
            String str = cache.get(1);
            System.out.println(str);
        }

        Thread.sleep(1000 * 2);
        {
            String str = cache.get(1);
            System.out.println(str);
        }
    }
}

运行Sample,main函数执行的结果是输出两行,第一行为aaa,第二行为null。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值