Producer/Consumer - producer adds data to collection without blocking, consumer consumes data from collection in batch

限于喜欢 提交于 2019-12-04 19:35:41

In the end I went with the LinkedBlockingQueue.

The producers add items into the queue.

The consumer will do a queue.poll() and keep the items into an internal collection. When the internal collection reaches 500 elements it is going to consume them in bulk. I can also set some timeouts. For instance, if X seconds has passed I'll consume the collection even if it has less items than required (eg. 220).

You could simply introduce an intermediate queue and consumer/producer, which would get the items from the queue filled by the producer, store them in a list, and once the list size is 500, put the list itself in the queue read by the consumer. The consumer would block until the next list of 500 items is available.

Of course you could also encapsulate this logic inside an object shared by the producers: the producers add their item to a "Batcher" object. The batcher object adds the items to a private list, and once the list size is 500, the batcher adds the list to the queue. Just make sure the batcher's addItem() method is synchronized. This would avoid the additional thread and queue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!