use of ratpack.func.BiAction in project ratpack by ratpack.
the class DefaultParallelBatch method forEach.
@Override
public Operation forEach(BiAction<? super Integer, ? super T> consumer) {
AtomicReference<Throwable> error = new AtomicReference<>();
AtomicBoolean done = new AtomicBoolean();
AtomicInteger wip = new AtomicInteger();
return Promise.async(d -> {
int i = 0;
Iterator<? extends Promise<T>> iterator = promises.iterator();
while (iterator.hasNext()) {
Promise<T> promise = iterator.next();
final int finalI = i++;
wip.incrementAndGet();
if (!iterator.hasNext()) {
done.set(true);
}
Execution.fork().onStart(execInit).onComplete(e -> {
if (wip.decrementAndGet() == 0 && done.get()) {
Throwable t = error.get();
if (t == null) {
d.success(null);
} else {
d.error(t);
}
}
}).start(e -> {
// noinspection ThrowableResultOfMethodCallIgnored
if (error.get() == null) {
promise.result(t -> {
if (t.isError()) {
Throwable thisError = t.getThrowable();
if (!error.compareAndSet(null, thisError)) {
// noinspection ThrowableResultOfMethodCallIgnored
Throwable firstError = error.get();
if (firstError != thisError) {
firstError.addSuppressed(thisError);
}
}
} else {
consumer.execute(finalI, t.getValue());
}
});
}
});
}
if (i == 0) {
d.success(null);
}
}).operation();
}
Aggregations