简单队列缓存

public enum SequenceEnum {
    SEQUENCE;

    SequenceEnum() {
    }

    private static final ConcurrentLinkedQueue<String> cache = new ConcurrentLinkedQueue<>();

    private static final ReentrantLock lock = new ReentrantLock();

    /**
     *
     * 出队
     */
    public String poll() {
        String seq = cache.poll();
        if(StringUtils.isEmpty(seq)){
            try {
                lock.lock();
                if(cache.isEmpty()){
                    offer(new SequenceGenerator().generateBatchSequence());
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally{
                lock.unlock();
            }
        }
        return cache.poll();
    }
    /**
     *
     * 入队
     */
    public void offer(String[] sequenceArray) {
        for (String sequence : sequenceArray) {
            cache.add(sequence);
        }
    }

    /**
     *
     * 队列数量太大,不可使用,因为遍历整个队列,耗时过长
     */
    public int size() {
        return cache.size();
    }

    /**
     *
     * 判空使用此方法
     */
    public boolean isEmpty(){
        return cache.isEmpty();
    }

}

 

posted @ 2019-06-22 01:51  me-ht  阅读(456)  评论(0编辑  收藏  举报