I believe that a cleaner solution is to support automatic dosing. that is, when the batch size is controlled by the speed of the incoming data.
For this you can use BlockingQueue
// unbound queue will not block the producer. final BlockingQueue<T> queue = new LinkedBlockingQueue<T>(); // to add an element. queue.add(element); // to get a batch of data List<T> list = new ArrayList<T>(maxElements); while(writing) { T t = queue.take(); // wait for at least one element. list.add(t); queue.drainTo(list, maxElements-1); // process list, eg write to a file. list.clear(); }
The advantage of this approach is that if the manufacturer works very slowly, you will not get elements that will have an unreasonably long period, but as the rate increases, the lot size naturally grows to keep up with the manufacturer, which means t must decide which size of the best packet to use.
source share