Java 中的环形缓冲区 [英] Ring Buffer in Java

查看:44
本文介绍了Java 中的环形缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个流式时间序列,我有兴趣保留最后 4 个元素,这意味着我希望能够弹出第一个,然后添加到最后.基本上我需要的是一个 环形缓冲区.

I have a streaming time series, of which I am interested in keeping the last 4 elements, which means I want to be able to pop the first, and add to the end. Essentially what I need is a ring buffer.

哪个 Java 集合最适合这个?矢量?

Which Java Collection is the best for this? Vector?

推荐答案

考虑 CircularFifoBuffer 来自 Apache Common.收藏.不像 Queue 你没有保持底层集合的有限大小,一旦达到限制就包装它.

Consider CircularFifoBuffer from Apache Common.Collections. Unlike Queue you don't have to maintain the limited size of underlying collection and wrap it once you hit the limit.

Buffer buf = new CircularFifoBuffer(4);
buf.add("A");
buf.add("B");
buf.add("C");
buf.add("D"); //ABCD
buf.add("E"); //BCDE

CircularFifoBuffer 会为您执行此操作,因为具有以下属性:

CircularFifoBuffer will do this for you because of the following properties:

  • CircularFifoBuffer 是一个先进先出的缓冲区,具有固定的大小,如果已满则替换其最旧的元素.
  • CircularFifoBuffer 的移除顺序基于插入命令;元素被删除的顺序与它们被删除的顺序相同添加.迭代顺序与移除顺序相同.
  • add(Object)、BoundedFifoBuffer.remove() 和BoundedFifoBuffer.get() 操作都在恒定时间内执行.所有其他操作都在线性时间或更糟的时间内执行.
  • CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.
  • The removal order of a CircularFifoBuffer is based on the insertion order; elements are removed in the same order in which they were added. The iteration order is the same as the removal order.
  • The add(Object), BoundedFifoBuffer.remove() and BoundedFifoBuffer.get() operations all perform in constant time. All other operations perform in linear time or worse.

但是,您也应该考虑它的局限性 - 例如,您不能将缺失的时间序列添加到此集合中,因为它不允许空值.

However you should consider it's limitations as well - for example, you can't add missing timeseries to this collection because it doens't allow nulls.

注意:当使用当前的Common Collections (4.*),你必须使用队列.像这样:

NOTE: When using current Common Collections (4.*), you have to use Queue. Like this:

Queue buf = new CircularFifoQueue(4);

这篇关于Java 中的环形缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆