我发现自己在重复这种模式,并且经常想知道它在Java中是惯用的,还是有更好的方法来实现这种行为。
问题:给定生产者/消费者设置,消费者想要处理成批的项目,所以它使用drainTo(),但是drainTo()将轮询现有项目并可能无法获得任何项目,为了避免这种情况,我在排水口前添加了take(),以确保它阻塞,直到至少有一个项目可用。
对于特定的数据集,我遇到的一个问题是,在许多用例中,批量大小通常是不规则的,在(1,N,1,N)之间交替。通常情况下,这是解决此问题的常用方法:
示例:
ArrayBlockingQueue<Foo> queue;
function void produce() {
while(true) {
queue.put(createFoo());
}
}
function void consumeBatchSpin() {
while(true) {
List<Foo> batch = Lists.newLinkedList();
queue.drainTo(batch);
doSomething(batch);
//the problem here is that if nothing is being produced, this loop will spin
}
}
function void consumeBatchTake() {
while(true) {
List<Foo> batch = Lists.newLinkedList();
batch.add(queue.take()); //force at least one item to be there
queue.drainTo(batch);
doSomething(batch);
}
}https://stackoverflow.com/questions/15192736
复制相似问题