[英]Java queue data structure with fixed size
I have a stream of network data coming in every few ms. 我每隔几毫秒就会收到一次网络数据流。 I need remove the first element, and add an element to the end of a fixed-sized list when this happens (ie "shift").
我需要删除第一个元素,并在发生这种情况时将元素添加到固定大小的列表的末尾(即“ shift”)。 The elements are simple
float
s. 元素是简单的
float
。
What data structure should I use, and is there an example usage? 我应该使用哪种数据结构,并且有示例用法? Thanks.
谢谢。
You've got several options. 您有几种选择。 The easiest would of course to just use a
Queue
, Java's got some implementations for you ( arrayblocking , concurrentlinked ). 当然,最简单的方法就是只使用
Queue
,Java为您提供了一些实现( arrayblocking , 并发链接 )。 You could overwrite any of them to add a shift method: 您可以覆盖其中任何一个以添加shift方法:
public E shift(E newElement) {
E old = take();
put(newElement);
return old;
}
To make this threadsafe, you'll need some synchronization. 为了使该线程安全,您需要进行一些同步。
If, for some reason, you prefer other collections, that's possible, too. 如果出于某种原因,您更喜欢其他系列,那也是可能的。 Mind that these might not be thread safe.
请注意,这些可能不是线程安全的。 I would not use an ArrayList, because of rather bad complexities, but a LinkedList should be fine.
由于复杂性很差,我不使用ArrayList,但是LinkedList应该很好。 Overwriting it would need this shift:
覆盖它需要这种转变:
public E shift(E newElement) {
E old = getFirst();
addLast(newElement);
return old;
}
As long as you use only the shift method, you can be sure of the fixed size. 只要仅使用shift方法,就可以确定大小固定。 If you want to force it, you'll have to overwrite more methods, of use a delegator.
如果要强制执行此操作,则必须覆盖使用委托者的更多方法。
I don't exactly know how you want to access the data from this ever-changing queue, but I suggest a LinkedBlockingQueue<Float>
or ArrayBlockingQueue<Float>
along with a thread to wait for & process input. 我不完全知道如何从不断变化的队列中访问数据,但是我建议使用
LinkedBlockingQueue<Float>
或ArrayBlockingQueue<Float>
以及一个线程来等待和处理输入。 You can add elements to the queue from any thread (eg your network thread), and process elements when they become available. 您可以从任何线程(例如,网络线程)将元素添加到队列中,并在元素可用时对其进行处理。 This way you are guaranteed to not loose any data unlike your current approach may (because data would be lost if more elements are written than processed unless you prevent writes while the data is being processed).
这样,您可以保证不会丢失与当前方法不同的任何数据(因为如果写入的元素多于处理的元素,则数据将会丢失,除非您防止在处理数据时进行写操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.