List of usage examples for com.google.common.util.concurrent Futures allAsList
@Beta @CheckReturnValue public static <V> ListenableFuture<List<V>> allAsList( Iterable<? extends ListenableFuture<? extends V>> futures)
From source file:com.google.idea.blaze.java.sync.source.PackageManifestReader.java
/** @return A map from java source absolute file path to declared package string. */ public Map<TargetKey, Map<ArtifactLocation, String>> readPackageManifestFiles(Project project, BlazeContext context, ArtifactLocationDecoder decoder, Map<TargetKey, ArtifactLocation> javaPackageManifests, ListeningExecutorService executorService) { Map<File, TargetKey> fileToLabelMap = Maps.newHashMap(); for (Map.Entry<TargetKey, ArtifactLocation> entry : javaPackageManifests.entrySet()) { TargetKey key = entry.getKey();// w w w . ja v a 2 s . c o m File file = decoder.decode(entry.getValue()); fileToLabelMap.put(file, key); } List<File> updatedFiles = Lists.newArrayList(); List<File> removedFiles = Lists.newArrayList(); fileDiffState = FileDiffer.updateFiles(fileDiffState, fileToLabelMap.keySet(), updatedFiles, removedFiles); ListenableFuture<?> fetchFuture = PrefetchService.getInstance().prefetchFiles(project, updatedFiles); if (!FutureUtil.waitForFuture(context, fetchFuture).timed("FetchPackageManifests") .withProgressMessage("Reading package manifests...").run().success()) { return null; } List<ListenableFuture<Void>> futures = Lists.newArrayList(); for (File file : updatedFiles) { futures.add(executorService.submit(() -> { Map<ArtifactLocation, String> manifest = parseManifestFile(file); manifestMap.put(fileToLabelMap.get(file), manifest); return null; })); } for (File file : removedFiles) { TargetKey key = this.fileToLabelMap.get(file); if (key != null) { manifestMap.remove(key); } } this.fileToLabelMap = fileToLabelMap; try { Futures.allAsList(futures).get(); } catch (ExecutionException | InterruptedException e) { LOG.error(e); throw new IllegalStateException("Could not read sources"); } return manifestMap; }
From source file:org.opendaylight.distributed.tx.impl.RollbackImpl.java
private static CheckedFuture<Void, DTxException.RollbackFailedException> aggregateRollbackFutures( final List<ListenableFuture<Void>> perNodeRollbackSubmitFutures) { final ListenableFuture<Void> aggregatedRollbackSubmitFuture = Futures .transform(Futures.allAsList(perNodeRollbackSubmitFutures), new Function<List<Void>, Void>() { @Nullable/* ww w.j a v a2 s . c o m*/ @Override public Void apply(@Nullable final List<Void> input) { return null; } }); return Futures.makeChecked(aggregatedRollbackSubmitFuture, new Function<Exception, DTxException.RollbackFailedException>() { @Nullable @Override public DTxException.RollbackFailedException apply(final Exception input) { return new DTxException.RollbackFailedException("Rollback submit failed", input); } }); }
From source file:org.opendaylight.openflowjava.protocol.impl.connection.SwitchConnectionProviderImpl.java
@Override public Future<List<Boolean>> startup() { LOGGER.debug("startup summoned"); ListenableFuture<List<Boolean>> result = SettableFuture.create(); try {//from w ww . j av a2s .c o m if (serverLot.isEmpty()) { throw new IllegalStateException("No servers configured"); } for (ServerFacade server : serverLot) { if (server.getIsOnlineFuture().isDone()) { throw new IllegalStateException("Servers already running"); } } if (switchConnectionHandler == null) { throw new IllegalStateException("switchConnectionHandler is not set"); } List<ListenableFuture<Boolean>> starterChain = new ArrayList<>(); for (ServerFacade server : serverLot) { new Thread(server).start(); ListenableFuture<Boolean> isOnlineFuture = server.getIsOnlineFuture(); starterChain.add(isOnlineFuture); } if (!starterChain.isEmpty()) { result = Futures.allAsList(starterChain); } else { throw new IllegalStateException("No servers configured"); } } catch (Exception e) { SettableFuture<List<Boolean>> exFuture = SettableFuture.create(); exFuture.setException(e); result = exFuture; } return result; }
From source file:org.asoem.greyfish.impl.environment.DefaultBasicEnvironment.java
private void executeAgents() { final List<ListenableFuture<?>> agentExecutions = Lists.newArrayList(); for (BasicAgent agent : agents) { agentExecutions.add(executorService.submit(agent)); }//from ww w . j a v a2 s .co m Futures.getUnchecked(Futures.allAsList(agentExecutions)); }
From source file:com.google.gapid.models.Devices.java
public void loadDevices() { Rpc.listen(Futures.transformAsync(client.getDevices(), paths -> { List<ListenableFuture<Service.Value>> results = Lists.newArrayList(); for (Path.Device path : paths) { results.add(client.get(Paths.device(path))); }/* www . j a v a2s. c o m*/ return Futures.allAsList(results); }), rpcController, new UiErrorCallback<List<Service.Value>, List<Device.Instance>, Void>(shell, LOG) { @Override protected ResultOrError<List<Device.Instance>, Void> onRpcThread(Result<List<Service.Value>> result) throws RpcException, ExecutionException { try { return success(result.get().stream().map(Service.Value::getDevice).collect(toList())); } catch (RpcException | ExecutionException e) { LOG.log(SEVERE, "LoadData error", e); return error(null); } } @Override protected void onUiThreadSuccess(List<Device.Instance> result) { updateDevices(result); } @Override protected void onUiThreadError(Void error) { updateDevices(null); } }); }
From source file:com.facebook.buck.distributed.DistBuildArtifactCacheImpl.java
private ListenableFuture<Map<RuleKey, CacheResult>> multiContainsAsync(List<RuleKey> ruleKeys) { List<ListenableFuture<ImmutableMap<RuleKey, CacheResult>>> requestResultsFutures = new ArrayList<>( ruleKeys.size() / MAX_RULEKEYS_IN_MULTI_CONTAINS_REQUEST + 1); while (ruleKeys.size() > 0) { int numKeysInCurrentRequest = Math.min(MAX_RULEKEYS_IN_MULTI_CONTAINS_REQUEST, ruleKeys.size()); LOG.verbose("Making multi-contains request for [%d] rulekeys.", numKeysInCurrentRequest); requestResultsFutures.add(remoteCache .multiContainsAsync(ImmutableSet.copyOf(ruleKeys.subList(0, numKeysInCurrentRequest)))); ruleKeys = ruleKeys.subList(numKeysInCurrentRequest, ruleKeys.size()); }//from w ww . ja v a2 s .c o m return Futures.transform(Futures.allAsList(requestResultsFutures), (List<Map<RuleKey, CacheResult>> requestResults) -> { Map<RuleKey, CacheResult> allResults = new HashMap<>(); for (Map<RuleKey, CacheResult> partResults : requestResults) { allResults.putAll(partResults); } return allResults; }, MoreExecutors.directExecutor()); }
From source file:com.flipkart.hydra.task.entities.WrapperCallable.java
protected Object getResponsesForArray() throws Exception { Object[] arr = (Object[]) loopVar; Map<Integer, ListenableFuture<Object>> futureMap = new HashMap<>(); for (int i = 0; i < arr.length; i++) { ListenableFuture<Object> future = getFuture(i, arr[i]); futureMap.put(i, future);/* w w w .j ava 2 s . c om*/ } ListenableFuture<List<Object>> compositeFuture = Futures.allAsList(futureMap.values()); compositeFuture.get(); Object[] responsesArray = new Object[arr.length]; for (int i = 0; i < arr.length; i++) { responsesArray[i] = futureMap.get(i); } return responsesArray; }
From source file:com.continuuity.weave.internal.kafka.client.SimpleKafkaClient.java
@Override public PreparePublish preparePublish(final String topic, final Compression compression) { final Map<Integer, MessageSetEncoder> encoders = Maps.newHashMap(); return new PreparePublish() { @Override/*from w ww .j a va2 s . c o m*/ public PreparePublish add(byte[] payload, Object partitionKey) { return add(ByteBuffer.wrap(payload), partitionKey); } @Override public PreparePublish add(ByteBuffer payload, Object partitionKey) { // TODO: Partition int partition = 0; MessageSetEncoder encoder = encoders.get(partition); if (encoder == null) { encoder = getEncoder(compression); encoders.put(partition, encoder); } encoder.add(ChannelBuffers.wrappedBuffer(payload)); return this; } @Override public ListenableFuture<?> publish() { List<ListenableFuture<?>> futures = Lists.newArrayListWithCapacity(encoders.size()); for (Map.Entry<Integer, MessageSetEncoder> entry : encoders.entrySet()) { futures.add(doPublish(topic, entry.getKey(), entry.getValue().finish())); } encoders.clear(); return Futures.allAsList(futures); } private ListenableFuture<?> doPublish(String topic, int partition, ChannelBuffer messageSet) { final KafkaRequest request = KafkaRequest.createProduce(topic, partition, messageSet); final SettableFuture<?> result = SettableFuture.create(); final ConnectionPool.ConnectResult connection = connectionPool .connect(getTopicBroker(topic, partition).getAddress()); connection.getChannelFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { future.getChannel().write(request) .addListener(getPublishChannelFutureListener(result, null, connection)); } catch (Exception e) { result.setException(e); } } }); return result; } }; }
From source file:io.druid.security.basic.CommonCacheNotifier.java
public void start() { exec.submit(() -> {/*from w ww . j av a2s . c o m*/ while (!Thread.interrupted()) { try { LOG.debug(callerName + ":Waiting for cache update notification"); Pair<String, byte[]> update = updateQueue.take(); String authorizer = update.lhs; byte[] serializedMap = update.rhs; BasicAuthDBConfig authorizerConfig = itemConfigMap.get(update.lhs); if (!authorizerConfig.isEnableCacheNotifications()) { continue; } LOG.debug(callerName + ":Sending cache update notifications"); // Best effort, if a notification fails, the remote node will eventually poll to update its state // We wait for responses however, to avoid flooding remote nodes with notifications. List<ListenableFuture<StatusResponseHolder>> futures = sendUpdate(authorizer, serializedMap); try { List<StatusResponseHolder> responses = Futures.allAsList(futures) .get(authorizerConfig.getCacheNotificationTimeout(), TimeUnit.MILLISECONDS); for (StatusResponseHolder response : responses) { LOG.debug(callerName + ":Got status: " + response.getStatus()); } } catch (Exception e) { LOG.makeAlert(e, callerName + ":Failed to get response for cache notification.").emit(); } LOG.debug(callerName + ":Received responses for cache update notifications."); } catch (Throwable t) { LOG.makeAlert(t, callerName + ":Error occured while handling updates for cachedUserMaps.") .emit(); } } }); }
From source file:org.grouplens.lenskit.eval.script.ConfigMethodInvoker.java
Object finishBuilder(final Builder<?> builder) { List<ListenableFuture<?>> deps = getDeps(builder); clearDeps(builder);//from w ww .ja v a 2s . c om if (deps.isEmpty()) { return builder.build(); } else { ListenableFuture<List<Object>> ideps = Futures.allAsList(deps); if (ideps.isDone()) { return builder.build(); } else { return Futures.transform(ideps, new Function<List<Object>, Object>() { @Nullable @Override public Object apply(@Nullable List<Object> input) { return builder.build(); } }); } } }