本文整理匯總了Java中com.google.common.util.concurrent.Futures.allAsList方法的典型用法代碼示例。如果您正苦於以下問題:Java Futures.allAsList方法的具體用法?Java Futures.allAsList怎麽用?Java Futures.allAsList使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.google.common.util.concurrent.Futures
的用法示例。
在下文中一共展示了Futures.allAsList方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: close
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@Override
public void close() throws IOException {
UploadPartRequest uploadPartRequest = new UploadPartRequest()
.withBucketName(bucketName)
.withKey(key)
.withPartNumber(partNumber)
.withPartSize(outputStream.size())
.withUploadId(multipartUpload.getUploadId())
.withInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
UploadPartResult uploadPartResult = client.uploadPart(uploadPartRequest);
etags.add(uploadPartResult.getPartETag());
ListenableFuture<List<Object>> future = Futures.allAsList(pendingUploads);
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
throw new IOException(e);
}
client.completeMultipartUpload(
new CompleteMultipartUploadRequest(
bucketName,
key,
multipartUpload.getUploadId(),
etags)
);
super.close();
}
示例2: abortAsyncAll
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@SuppressWarnings({"unchecked", "rawtypes"})
private ListenableFuture<Void> abortAsyncAll() {
final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohorts.size()];
int i = 0;
for (final DOMStoreThreePhaseCommitCohort cohort : cohorts) {
ops[i++] = cohort.abort();
}
/*
* We are returning all futures as list, not only succeeded ones in
* order to fail composite future if any of them failed.
* See Futures.allAsList for this description.
*/
return (ListenableFuture) Futures.allAsList(ops);
}
示例3: readAllData
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures =
new ArrayList<>(allShardNames.size());
for (String shardName : allShardNames) {
futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
}
final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
aggregateFuture = Futures.transform(listFuture,
(Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
try {
return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
txContextFactory.getActorContext().getSchemaContext(),
txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
} catch (DataValidationFailedException e) {
throw new IllegalArgumentException("Failed to aggregate", e);
}
}, MoreExecutors.directExecutor());
return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
}
示例4: findAllAsync
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
private ListenableFuture<List<TsKvEntry>> findAllAsync(EntityId entityId, TsKvQuery query) {
if (query.getAggregation() == Aggregation.NONE) {
return findAllAsyncWithLimit(entityId, query);
} else {
long stepTs = query.getStartTs();
List<ListenableFuture<Optional<TsKvEntry>>> futures = new ArrayList<>();
while (stepTs < query.getEndTs()) {
long startTs = stepTs;
long endTs = stepTs + query.getInterval();
long ts = startTs + (endTs - startTs) / 2;
futures.add(findAndAggregateAsync(entityId, query.getKey(), startTs, endTs, ts, query.getAggregation()));
stepTs = endTs;
}
ListenableFuture<List<Optional<TsKvEntry>>> future = Futures.allAsList(futures);
return Futures.transform(future, new Function<List<Optional<TsKvEntry>>, List<TsKvEntry>>() {
@Nullable
@Override
public List<TsKvEntry> apply(@Nullable List<Optional<TsKvEntry>> results) {
if (results == null || results.isEmpty()) {
return null;
}
return results.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}
}, service);
}
}
示例5: deleteEntityRelations
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@Override
public ListenableFuture<Boolean> deleteEntityRelations(EntityId entity) {
log.trace("Executing deleteEntityRelations [{}]", entity);
validate(entity);
List<ListenableFuture<List<EntityRelation>>> inboundRelationsList = new ArrayList<>();
for (RelationTypeGroup typeGroup : RelationTypeGroup.values()) {
inboundRelationsList.add(relationDao.findAllByTo(entity, typeGroup));
}
ListenableFuture<List<List<EntityRelation>>> inboundRelations = Futures.allAsList(inboundRelationsList);
ListenableFuture<List<Boolean>> inboundDeletions = Futures.transform(inboundRelations, new AsyncFunction<List<List<EntityRelation>>, List<Boolean>>() {
@Override
public ListenableFuture<List<Boolean>> apply(List<List<EntityRelation>> relations) throws Exception {
List<ListenableFuture<Boolean>> results = new ArrayList<>();
for (List<EntityRelation> relationList : relations) {
relationList.stream().forEach(relation -> results.add(relationDao.deleteRelation(relation)));
}
return Futures.allAsList(results);
}
});
ListenableFuture<Boolean> inboundFuture = Futures.transform(inboundDeletions, getListToBooleanFunction());
ListenableFuture<Boolean> outboundFuture = relationDao.deleteOutboundRelations(entity);
return Futures.transform(Futures.allAsList(Arrays.asList(inboundFuture, outboundFuture)), getListToBooleanFunction());
}
示例6: findAllAsync
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
private ListenableFuture<List<TsKvEntry>> findAllAsync(EntityId entityId, TsKvQuery query) {
if (query.getAggregation() == Aggregation.NONE) {
return findAllAsyncWithLimit(entityId, query);
} else {
long step = Math.max(query.getInterval(), MIN_AGGREGATION_STEP_MS);
long stepTs = query.getStartTs();
List<ListenableFuture<Optional<TsKvEntry>>> futures = new ArrayList<>();
while (stepTs < query.getEndTs()) {
long startTs = stepTs;
long endTs = stepTs + step;
TsKvQuery subQuery = new BaseTsKvQuery(query.getKey(), startTs, endTs, step, 1, query.getAggregation());
futures.add(findAndAggregateAsync(entityId, subQuery, toPartitionTs(startTs), toPartitionTs(endTs)));
stepTs = endTs;
}
ListenableFuture<List<Optional<TsKvEntry>>> future = Futures.allAsList(futures);
return Futures.transform(future, new Function<List<Optional<TsKvEntry>>, List<TsKvEntry>>() {
@Nullable
@Override
public List<TsKvEntry> apply(@Nullable List<Optional<TsKvEntry>> input) {
return input.stream().filter(v -> v.isPresent()).map(v -> v.get()).collect(Collectors.toList());
}
}, readResultsProcessingExecutor);
}
}
示例7: getFetchChunksAsyncFunction
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
private AsyncFunction<List<Long>, List<ResultSet>> getFetchChunksAsyncFunction(EntityId entityId, String key, Aggregation aggregation, long startTs, long endTs) {
return partitions -> {
try {
PreparedStatement proto = getFetchStmt(aggregation);
List<ResultSetFuture> futures = new ArrayList<>(partitions.size());
for (Long partition : partitions) {
log.trace("Fetching data for partition [{}] for entityType {} and entityId {}", partition, entityId.getEntityType(), entityId.getId());
BoundStatement stmt = proto.bind();
stmt.setString(0, entityId.getEntityType().name());
stmt.setUUID(1, entityId.getId());
stmt.setString(2, key);
stmt.setLong(3, partition);
stmt.setLong(4, startTs);
stmt.setLong(5, endTs);
log.debug("Generated query [{}] for entityType {} and entityId {}", stmt, entityId.getEntityType(), entityId.getId());
futures.add(executeAsyncRead(stmt));
}
return Futures.allAsList(futures);
} catch (Throwable e) {
log.error("Failed to fetch data", e);
throw e;
}
};
}
示例8: shelfToBooks
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@SchemaModification(addField = "books", onType = Shelf.class)
ListenableFuture<List<Book>> shelfToBooks(
Shelf shelf, BookServiceGrpc.BookServiceFutureStub bookClient) {
// TODO: use a data loader or batch endpoint
return Futures.allAsList(
shelf
.getBookIdsList()
.stream()
.map(id -> bookClient.getBook(GetBookRequest.newBuilder().setId(id).build()))
.collect(ImmutableList.toImmutableList()));
}
示例9: runWithAvailableThreads
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
/**
* Similar to {@link #runWithAvailableThreads(ThreadPoolExecutor, int, Collection)}
* but this function will return a Future that wraps the futures of each callable
*
* @param executor executor that is used to execute the callableList
* @param poolSize the corePoolSize of the given executor
* @param callableCollection a collection of callable that should be executed
* @param mergeFunction function that will be applied to merge the results of multiple callable in case that they are
* executed together if the threadPool is exhausted
* @param <T> type of the final result
* @return a future that will return a list of the results of the callableList
* @throws RejectedExecutionException
*/
public static <T> ListenableFuture<List<T>> runWithAvailableThreads(
ThreadPoolExecutor executor,
int poolSize,
Collection<Callable<T>> callableCollection,
final Function<List<T>, T> mergeFunction) throws RejectedExecutionException {
ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executor);
List<ListenableFuture<T>> futures;
int availableThreads = Math.max(poolSize - executor.getActiveCount(), 1);
if (availableThreads < callableCollection.size()) {
Iterable<List<Callable<T>>> partition = Iterables.partition(callableCollection,
callableCollection.size() / availableThreads);
futures = new ArrayList<>(availableThreads + 1);
for (final List<Callable<T>> callableList : partition) {
futures.add(listeningExecutorService.submit(new Callable<T>() {
@Override
public T call() throws Exception {
List<T> results = new ArrayList<T>(callableList.size());
for (Callable<T> tCallable : callableList) {
results.add(tCallable.call());
}
return mergeFunction.apply(results);
}
}));
}
} else {
futures = new ArrayList<>(callableCollection.size());
for (Callable<T> callable : callableCollection) {
futures.add(listeningExecutorService.submit(callable));
}
}
return Futures.allAsList(futures);
}
示例10: uniteOptimistically
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
/**
* Requests the hub to return a single united, optimistic {@link RedFuture} instance.
* Optimistic means that the returned future expects all the hub's tracked futures to resolve successfully,
* namely, it will be:
* Successfully resolved if and when all the hub's tracked futures are successfully resolved.
* Failed if and when the first of the hub's tracked futures is failed.
*
* @return the united future.
*/
public RedFuture uniteOptimistically() {
RedFuture validated = validate();
if (validated != null) {
return validated;
}
ListenableFuture<List<Object>> collection = Futures.allAsList(listenableFutures);
OpenRedFuture future = RedFuture.future();
future.follow(collection);
return future;
}
示例11: sendMessageToShardManagers
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
private <T> ListenableFuture<List<T>> sendMessageToShardManagers(Object message) {
Timeout timeout = SHARD_MGR_TIMEOUT;
ListenableFuture<T> configFuture = ask(configDataStore.getActorContext().getShardManager(), message, timeout);
ListenableFuture<T> operFuture = ask(operDataStore.getActorContext().getShardManager(), message, timeout);
return Futures.allAsList(configFuture, operFuture);
}
示例12: makeBreakfast
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@Override
public Future<RpcResult<Void>> makeBreakfast(EggsType eggsType, Class<? extends ToastType> toastType,
int toastDoneness) {
// Call makeToast and use JdkFutureAdapters to convert the Future to a ListenableFuture, The
// OpendaylightToaster impl already returns a ListenableFuture so the conversion is actually a no-op.
ListenableFuture<RpcResult<Void>> makeToastFuture = JdkFutureAdapters
.listenInPoolThread(makeToast(toastType, toastDoneness), executor);
ListenableFuture<RpcResult<Void>> makeEggsFuture = makeEggs(eggsType);
// Combine the 2 ListenableFutures into 1 containing a list RpcResults.
ListenableFuture<List<RpcResult<Void>>> combinedFutures = Futures
.allAsList(ImmutableList.of(makeToastFuture, makeEggsFuture));
// Then transform the RpcResults into 1.
return Futures.transformAsync(combinedFutures, results -> {
boolean atLeastOneSucceeded = false;
Builder<RpcError> errorList = ImmutableList.builder();
for (RpcResult<Void> result : results) {
if (result.isSuccessful()) {
atLeastOneSucceeded = true;
}
if (result.getErrors() != null) {
errorList.addAll(result.getErrors());
}
}
return Futures.immediateFuture(RpcResultBuilder.<Void>status(atLeastOneSucceeded)
.withRpcErrors(errorList.build()).build());
});
}
示例13: removeAll
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@Override
public ListenableFuture<List<Void>> removeAll(EntityId entityId, String attributeType, List<String> keys) {
List<ListenableFuture<Void>> futures = keys
.stream()
.map(key -> delete(entityId, attributeType, key))
.collect(Collectors.toList());
return Futures.allAsList(futures);
}
示例14: findLatest
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@Override
public ListenableFuture<List<TsKvEntry>> findLatest(EntityId entityId, Collection<String> keys) {
validate(entityId);
List<ListenableFuture<TsKvEntry>> futures = Lists.newArrayListWithExpectedSize(keys.size());
keys.forEach(key -> Validator.validateString(key, "Incorrect key " + key));
keys.forEach(key -> futures.add(timeseriesDao.findLatest(entityId, key)));
return Futures.allAsList(futures);
}
示例15: save
import com.google.common.util.concurrent.Futures; //導入方法依賴的package包/類
@Override
public ListenableFuture<List<Void>> save(EntityId entityId, TsKvEntry tsKvEntry) {
validate(entityId);
if (tsKvEntry == null) {
throw new IncorrectParameterException("Key value entry can't be null");
}
List<ListenableFuture<Void>> futures = Lists.newArrayListWithExpectedSize(INSERTS_PER_ENTRY);
saveAndRegisterFutures(futures, entityId, tsKvEntry, 0L);
return Futures.allAsList(futures);
}