?【Java技術專區】「延時佇列專題」教你如何使用【精巧好用】的DelayQueue

李浩宇Alex發表於2021-08-06

延時佇列前提

  1. 定時關閉空閒連線:伺服器中,有很多客戶端的連線,空閒一段時間之後需要關閉之。
  2. 定時清除額外快取:快取中的物件,超過了空閒時間,需要從快取中移出。
  3. 實現任務超時處理:在網路協議滑動視窗請求應答式互動時,處理超時未響應的請求。
  4. 應用在session超時管理:網路應答通訊協議的請求超時處理。

痛點方案機制

  • 一種比較暴力的辦法就是,使用一個後臺執行緒,遍歷所有物件,挨個檢查。這種笨笨的辦法簡單好用,但是物件數量過多時,可能存在效能問題,檢查間隔時間不好設定,間隔時間過大,影響精確度,多小則存在效率問題。

  • 而且做不到按超時的時間順序處理。 這場景,使用DelayQueue最適合了。

DelayQueue是java.util.concurrent中提供的一個很有意思的類。很巧妙,非常棒!但是java doc和Java SE 5.0的source中都沒有Sample。我最初在閱讀ScheduledThreadPoolExecutor原始碼時,發現DelayQueue的妙用。

本文將會對DelayQueue做一個介紹,然後列舉應用場景。並且提供一個Delayed介面的實現和Sample程式碼。

  • DelayQueue是一個BlockingQueue,其特化的引數是Delayed。

  • Delayed擴充套件了Comparable介面,比較的基準為延時的時間值,Delayed介面的實現類getDelay的返回值應為固定值(final)。

  • DelayQueue內部是使用PriorityQueue實現的。

  • DelayQueue = BlockingQueue + PriorityQueue + Delayed

DelayQueue的關鍵元素BlockingQueue、PriorityQueue、Delayed。可以這麼說,DelayQueue是一個使用優先佇列(PriorityQueue)實現的BlockingQueue,優先佇列的比較基準值是時間。

基本定義如下

public interface Comparable<T> {
    public int compareTo(T o);
}

public interface Delayed extends Comparable<Delayed> {
    long getDelay(TimeUnit unit);
}

public class DelayQueue<E extends Delayed> implements BlockingQueue<E> { 
    private final PriorityQueue<E> q = new PriorityQueue<E>();
}

DelayQueue內部的實現使用了一個優先佇列。當呼叫DelayQueue的offer方法時,把Delayed物件加入到優先佇列q中。如下:

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();
        return true;
    } finally {
        lock.unlock();
    }
}

DelayQueue的take方法,把優先佇列q的first拿出來(peek),如果沒有達到延時閥值,則進行await處理。如下:

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

以下是Sample,是一個快取的簡單實現。共包括三個類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;
    }
}

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

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函式。

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
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。

延時佇列引數配置熱重新整理

配置中心勿噴,場景不一樣

  • 快取延時佇列的資訊都存在配置檔案中,比如快取數量配置、延時超時時間,事件的超時時間等等。當需要該這些配置的值時都需要重新啟動程式,改動的配置才會生效,有時候線上的應用不能容忍這種停服。

  • Apache Common Configuration給我們提供了可以檢測檔案修改後配置可短時間生效的功能。具體用法如下:

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;

public class SystemConfig {
    private static Logger logger = Logger.getLogger(SystemConfig.class);
    private static  PropertiesConfiguration config;
    static {
        try {
            //例項化一個PropertiesConfiguration
            config = new PropertiesConfiguration("/Users/hzwangxx/
												 IdeaProjects/app-test/src/main/resources/conf.properties");
            //設定reload策略,這裡用當檔案被修改之後reload(預設5s中檢測一次)
            config.setReloadingStrategy(new FileChangedReloadingStrategy());
        } catch (ConfigurationException e) {
            logger.error("init static block error. ", e);
        }
    }

    public static synchronized String getProperty(String key) {
        return (String) config.getProperty(key);
    }

    public static void main(String[] args) throws InterruptedException {
        for (;;) {
            System.out.println(SystemConfig.getProperty("key"));
            Thread.sleep(2000);
        }
    }
}

相關文章