DelayQueue遅延キュー - キャッシュを実装します

遅延ブロッキングキューDelayQueue

DelayQueueは、キュー要素、ブロックのサポートを得遅れで
、プライオリティキュー優先度つきキュー記憶素子の内部使用を
要素が遅れるインタフェースを実装する必要がありながら、彼らはキューから現在の要素を取得することができます前に、要素を作成するときに頻度を指定することができ、遅延が満了した場合にのみ要素がキューから抽出されます。

利用シナリオ

  • キャッシュシステム:DelayQueueキューは述べたキャッシュ内の遅延素子から取得することができる期限が切れています
  • タスクスケジューリングのタイミング:メッセージを送信した後、1分

遅延キューに基づくキャッシュシステムを実現するために

遅延要素がキューに追加され、インターフェースの実装は、遅延します

public class CacheItem implements Delayed{
    private long expireTime;
    
    private long currentTime;
    
    private String key;
    
    public String getKey() {
        return key;
    }
    
    public CacheItem(String key,long expireTime) {
        this.key = key;
        this.expireTime = expireTime;
        this.currentTime = System.currentTimeMillis();
    }

    /**
     * 比较方法,用于排序
     * 过期时间长的放队尾,时间短的放队首
     */
    @Override
    public int compareTo(Delayed o) {
        if(this.getDelay(TimeUnit.MICROSECONDS) > o.getDelay(TimeUnit.MICROSECONDS))
            return 1;
        if(this.getDelay(TimeUnit.MICROSECONDS) > o.getDelay(TimeUnit.MICROSECONDS))
            return -1;
        return 0;
    }

    /**
     * 计算剩余的过期时间
     * 大于0说明没有过期
     */
    @Override
    public long getDelay(TimeUnit unit) {
        
        return expireTime - unit.MILLISECONDS.toSeconds(System.currentTimeMillis()-currentTime);
        
    }

}

キャッシュの実装

public class DelayQueueDemo {
    static class Cache implements Runnable{
        private Map<String,String> itemMap = new HashMap<>();
    
        private DelayQueue<CacheItem> delayQueue = new DelayQueue<>();
        
        private boolean stop = false;
        
        // 初始化后就开始检测
        public Cache() {
            new Thread(this).start();
        }
        
        public void add(String key,String value,long expireTime) {
            CacheItem item = new CacheItem(key,expireTime);
            itemMap.put(key, value);
            delayQueue.add(item);
            
        }
        
        public String get(String key) {
            return itemMap.get(key);
        }
        
        public void shutdown() {
            stop = true;
        }
        
        // 开启多线程,检测缓存是否过期
        @Override
        public void run() {
            while(!stop) {
                CacheItem item = delayQueue.poll();
                if(item != null) {
                    // 缓存过期
                     itemMap.remove(item.getKey());
                     System.out.println("delete expired key:"+item.getKey());
                }
            }
            System.out.println("Cache stop");
        }
    }
    
    public static void main(String[] args) throws Exception{
        Cache cache = new Cache();
        cache.add("a", "1", 1);
        cache.add("b", "2", 2);
        cache.add("c", "3", 2);
        cache.add("d", "4", 4);
        cache.add("e", "5", 6);
        
        while(true) {
            String a = cache.get("a");
            String b = cache.get("b");
            String c = cache.get("c");
            String d = cache.get("d");
            String e = cache.get("e");
            
            if(a == null && b == null && c == null && d == null && e == null) {
                break;
            }
        }
        
        TimeUnit.SECONDS.sleep(1);
        cache.shutdown();
    }
    
}

原則セクションでは、遅延キューを説明します

  • リエントラントロック ReentrantLock
  • プライオリティキュー PriorityQueue

リファレンス接続

おすすめ

転載: www.cnblogs.com/watertreestar/p/11780249.html