Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 individual 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.

like image 489
Guido Avatar asked Nov 04 '22 16:11

Guido


1 Answers

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
}
like image 196
Andreas Dolk Avatar answered Nov 11 '22 02:11

Andreas Dolk