Deque的使用實(shí)例

雙向隊(duì)列(Deque),是Queue的一個(gè)子接口,雙向隊(duì)列是指該隊(duì)列兩端的元素既能入隊(duì)(offer)也能出隊(duì)(poll)。使用場(chǎng)景比如工作竊取,比如限流。

限流實(shí)例

使用deque來(lái)限流,其中timeIntervalInMs為事件窗口,maxLimit為該事件窗口的最大值。

public class MyRateLimiter {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoRateLimiter.class);

    private final Deque<Long> queue;

    private long timeIntervalInMs;

    public MyRateLimiter(long timeIntervalInMs, int maxLimit) {
        this.timeIntervalInMs = timeIntervalInMs;
        this.queue = new LinkedBlockingDeque<Long>(maxLimit);
    }

    public boolean incrAndReachLimit(){
        long currentTimeMillis = System.currentTimeMillis();
        boolean success = queue.offerFirst(currentTimeMillis);
        if(success){
            //沒(méi)有超過(guò)maxLimit
            return false;
        }

        synchronized (this){
            //queue is full
            long last = queue.getLast();

            //還在時(shí)間窗口內(nèi),超過(guò)maxLimit
            if (currentTimeMillis - last < timeIntervalInMs) {
                return true;
            }
            LOGGER.info("time window expired,current:{},last:{}",currentTimeMillis,last);
            //超過(guò)時(shí)間窗口了,超過(guò)maxLimit的情況下,重置時(shí)間窗口
            queue.removeLast();
            queue.addFirst(currentTimeMillis);

            return false;
        }

    }
}

測(cè)試

@Test
    public void testDeque() throws InterruptedException {
        DemoRateLimiter limiter = new DemoRateLimiter(5*1000,3);
        Callable<Void> test = new Callable<Void>(){

            @Override
            public Void call() throws Exception {
                for(int i=0;i<1000;i++){
                    LOGGER.info("result:{}",limiter.incrAndReachLimit());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }
        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        pool.invokeAll(Arrays.asList(test,test,test,test,test));

        Thread.sleep(100000);
    }

小結(jié)

這里使用了Deque的容量來(lái)作為時(shí)間窗口的限流大小,利用兩端來(lái)判斷時(shí)間窗口,相對(duì)來(lái)講有點(diǎn)巧妙。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評(píng)論 19 139
  • 阻塞隊(duì)列(BlockingQueue)是一個(gè)支持兩個(gè)附加操作的隊(duì)列。這兩個(gè)附加的操作是:在隊(duì)列為空時(shí),獲取元素的線...
    端木軒閱讀 1,058評(píng)論 0 2
  • 深入學(xué)習(xí)Java之LinkedList 前言 LinkedList,作為最常用的List接口的實(shí)現(xiàn)類(lèi)之一,與Arr...
    顏洛濱閱讀 712評(píng)論 0 1
  • 相關(guān)文章Java并發(fā)編程(一)線程定義、狀態(tài)和屬性 Java并發(fā)編程(二)同步Java并發(fā)編程(三)volatil...
    劉望舒閱讀 5,288評(píng)論 1 31
  • 昨晚跟一附院腫瘤內(nèi)科的藍(lán)東老師值班,一患者腹痛明顯,對(duì)未予其止痛藥很不滿,要求肌肉注射止痛藥,并且拒用口服藥。藍(lán)老...
    阿超雙螺旋閱讀 351評(píng)論 0 4

友情鏈接更多精彩內(nèi)容