Collections with several constraints (time and size) in Java
I have two processes (producer/consumer). The first one puts elements in a Collection, the second one reads them.
I want the second process not to read every indivi开发者_Go百科dual element, but wait until:
- There are at least N elements in the collection OR
- The last element was received T seconds ago.
Is there any Collection in Java 5+ that allows this kind of behaviour? I was thinking about an implementation of Queue, but I've only found DelayQueue that is not exactly what I need.
Thank you.
I'd implement an observable collection. The second process will listen to events, signalling that N
elements are in the collection (events based on size
attribute) and that no element has been added for a certain time (needs a timer, that is reset on every add
operation)
Something like this (just drafting the size requirement):
public ObservableCollection implements Collection {
private int sizetrigger;
private Collection collection;
private Collection<Listener> listeners = new ArrayList<Listener>();
public ObservableCollection(Collection collection) {
this.collection = collection;
}
@Override
boolean add(Object element) {
collection.add(element);
if (size >= sizeTrigger) {
fireSizeEvent();
}
}
private fireSizeEvent() {
for(Listener listener:listeners) {
listener.thresholdReached(this);
}
}
// addListener, removeListener and implementations of interface methods
}
精彩评论