package com.google.common.util.concurrent;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static java.util.Collections.unmodifiableList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.Future;
import org.checkerframework.checker.nullness.qual.Nullable;
@GwtCompatible(emulated = true)
abstract class CollectionFuture<V, C> extends AggregateFuture<V, C> {
private List<Present<V>> values;
CollectionFuture(
ImmutableCollection<? extends ListenableFuture<? extends V>> futures,
boolean allMustSucceed) {
super(futures, allMustSucceed, true);
List<Present<V>> values =
futures.isEmpty()
? ImmutableList.<Present<V>>of()
: Lists.<Present<V>>newArrayListWithCapacity(futures.size());
for (int i = 0; i < futures.size(); ++i) {
values.add(null);
}
this.values = values;
}
@Override
final void collectOneValue(int index, @Nullable V returnValue) {
List<Present<V>> localValues = values;
if (localValues != null) {
localValues.set(index, new Present<>(returnValue));
}
}
@Override
final void handleAllCompleted() {
List<Present<V>> localValues = values;
if (localValues != null) {
set(combine(localValues));
}
}
@Override
void releaseResources(ReleaseResourcesReason reason) {
super.releaseResources(reason);
this.values = null;
}
abstract C combine(List<Present<V>> values);
static final class ListFuture<V> extends CollectionFuture<V, List<V>> {
ListFuture(
ImmutableCollection<? extends ListenableFuture<? extends V>> futures,
boolean allMustSucceed) {
super(futures, allMustSucceed);
init();
}
@Override
public List<V> combine(List<Present<V>> values) {
List<V> result = newArrayListWithCapacity(values.size());
for (Present<V> element : values) {
result.add(element != null ? element.value : null);
}
return unmodifiableList(result);
}
}
private static final class Present<V> {
V value;
Present(V value) {
this.value = value;
}
}
}