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.cloudera.oryx.kmeans.computation.local.ClusteringEvaluation.java
@Override public List<KMeansEvaluationData> call() throws InterruptedException, ExecutionException { Config config = ConfigUtils.getDefaultConfig(); EvaluationSettings settings = EvaluationSettings.create(config); ListeningExecutorService exec = MoreExecutors .listeningDecorator(Executors.newFixedThreadPool(config.getInt("model.parallelism"), new ThreadFactoryBuilder().setNameFormat("KMEANS-%d").setDaemon(true).build())); List<ListenableFuture<KMeansEvaluationData>> futures = Lists.newArrayList(); for (Integer nc : settings.getKValues()) { int loops = nc == 1 ? 1 : settings.getReplications(); for (int i = 0; i < loops; i++) { futures.add(exec.submit(new EvaluationRun(weightedPoints, nc, i, settings))); }/* www. jav a 2s .c o m*/ } try { List<KMeansEvaluationData> evalData = Futures.allAsList(futures).get(); KMeansEvalStrategy evalStrategy = settings.getEvalStrategy(); if (evalStrategy != null) { List<ClusterValidityStatistics> best = evalStrategy.evaluate( Lists.transform(evalData, new Function<KMeansEvaluationData, ClusterValidityStatistics>() { @Override public ClusterValidityStatistics apply(KMeansEvaluationData input) { return input.getClusterValidityStatistics(); } })); if (best.size() == 1) { ClusterValidityStatistics cvs = best.get(0); for (KMeansEvaluationData ed : evalData) { if (cvs.getK() == ed.getK() && cvs.getReplica() == ed.getReplica()) { return ImmutableList.of(ed); } } } } return evalData; } finally { ExecutorUtils.shutdownAndAwait(exec); } }
From source file:dagger2.producers.internal.SetProducer.java
/** * Returns a future {@link Set} whose iteration order is that of the elements given by each of the * producers, which are invoked in the order given at creation. * * <p>If any of the delegate sets, or any elements therein, are null, then this future will fail * with a NullPointerException./*from ww w . ja v a 2 s . co m*/ * * <p>Canceling this future will attempt to cancel all of the component futures, and if any of the * delegate futures fails or is canceled, this one is, too. * * @throws NullPointerException if any of the delegate producers return null */ @Override public ListenableFuture<Set<T>> compute() { List<ListenableFuture<Set<T>>> futureSets = new ArrayList<ListenableFuture<Set<T>>>( contributingProducers.size()); for (Producer<Set<T>> producer : contributingProducers) { ListenableFuture<Set<T>> futureSet = producer.get(); if (futureSet == null) { throw new NullPointerException(producer + " returned null"); } futureSets.add(futureSet); } return Futures.transform(Futures.allAsList(futureSets), new Function<List<Set<T>>, Set<T>>() { @Override public Set<T> apply(List<Set<T>> sets) { ImmutableSet.Builder<T> builder = ImmutableSet.builder(); for (Set<T> set : sets) { builder.addAll(set); } return builder.build(); } }); }
From source file:dagger.producers.internal.MapProducer.java
@Override public ListenableFuture<Map<K, V>> compute() { return Futures.transformAsync(mapProducerProducer.get(), new AsyncFunction<Map<K, Producer<V>>, Map<K, V>>() { @Override/*w w w . j a v a2 s.c o m*/ public ListenableFuture<Map<K, V>> apply(final Map<K, Producer<V>> map) { // TODO(beder): Use Futures.whenAllComplete when Guava 20 is released. return transform( Futures.allAsList( Iterables.transform(map.entrySet(), MapProducer.<K, V>entryUnwrapper())), new Function<List<Map.Entry<K, V>>, Map<K, V>>() { @Override public Map<K, V> apply(List<Map.Entry<K, V>> entries) { return ImmutableMap.copyOf(entries); } }, directExecutor()); } }, directExecutor()); }
From source file:com.facebook.buck.artifact_cache.MultiArtifactCache.java
private static ListenableFuture<Void> storeToCaches(ImmutableList<ArtifactCache> caches, ArtifactInfo info, BorrowablePath output) {//from w ww . j a v a 2 s . c o m // TODO(cjhopman): support BorrowablePath with multiple writable caches. if (caches.size() != 1) { output = BorrowablePath.notBorrowablePath(output.getPath()); } List<ListenableFuture<Void>> storeFutures = Lists.newArrayListWithExpectedSize(caches.size()); for (ArtifactCache artifactCache : caches) { storeFutures.add(artifactCache.store(info, output)); } // Aggregate future to ensure all store operations have completed. return Futures.transform(Futures.allAsList(storeFutures), Functions.<Void>constant(null)); }
From source file:com.google.gerrit.server.index.change.ChangeIndexer.java
public static CheckedFuture<?, IOException> allAsList(List<? extends ListenableFuture<?>> futures) { // allAsList propagates the first seen exception, wrapped in // ExecutionException, so we can reuse the same mapper as for a single // future. Assume the actual contents of the exception are not useful to // callers. All exceptions are already logged by IndexTask. return Futures.makeChecked(Futures.allAsList(futures), MAPPER); }
From source file:com.google.javascript.jscomp.PrebuildAst.java
void prebuild(Iterable<CompilerInput> allInputs) { ThreadFactory threadFactory = new ThreadFactory() { @Override/*from w w w .j av a2s. c o m*/ public Thread newThread(Runnable r) { Thread t = new Thread(null, r, "jscompiler-PrebuildAst", CompilerExecutor.COMPILER_STACK_SIZE); t.setDaemon(true); // Do not prevent the JVM from exiting. return t; } }; ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(numParallelThreads, numParallelThreads, Integer.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); ListeningExecutorService executorService = MoreExecutors.listeningDecorator(poolExecutor); List<ListenableFuture<?>> futureList = new ArrayList<>(Iterables.size(allInputs)); // TODO(moz): Support canceling all parsing on the first halting error for (final CompilerInput input : allInputs) { futureList.add(executorService.submit(new Runnable() { @Override public void run() { input.getAstRoot(compiler); } })); } poolExecutor.shutdown(); try { Futures.allAsList(futureList).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }
From source file:org.apache.druid.client.cache.BackgroundCachePopulator.java
@Override public <T, CacheType> Sequence<T> wrap(final Sequence<T> sequence, final Function<T, CacheType> cacheFn, final Cache cache, final Cache.NamedKey cacheKey) { final List<ListenableFuture<CacheType>> cacheFutures = new ArrayList<>(); final Sequence<T> wrappedSequence = Sequences.map(sequence, input -> { cacheFutures.add(exec.submit(() -> cacheFn.apply(input))); return input; });/*w w w.ja v a2s .co m*/ return Sequences.withEffect(wrappedSequence, () -> { Futures.addCallback(Futures.allAsList(cacheFutures), new FutureCallback<List<CacheType>>() { @Override public void onSuccess(List<CacheType> results) { populateCache(cache, cacheKey, results); // Help out GC by making sure all references are gone cacheFutures.clear(); } @Override public void onFailure(Throwable t) { log.error(t, "Background caching failed"); } }, exec); }, MoreExecutors.sameThreadExecutor()); }
From source file:org.thingsboard.server.dao.attributes.BaseAttributesService.java
@Override public ListenableFuture<List<Void>> save(TenantId tenantId, EntityId entityId, String scope, List<AttributeKvEntry> attributes) { validate(entityId, scope);/*from w ww . j a v a2 s .c o m*/ attributes.forEach(attribute -> validate(attribute)); List<ListenableFuture<Void>> futures = Lists.newArrayListWithExpectedSize(attributes.size()); for (AttributeKvEntry attribute : attributes) { futures.add(attributesDao.save(tenantId, entityId, scope, attribute)); } return Futures.allAsList(futures); }
From source file:com.webbfontaine.valuewebb.irms.impl.risk.data.RiskResultCollector.java
public void calculateResults() { if (results == null) { LOGGER.trace("Calculating 'Risk Collector' state based on results: {}", results); ListenableFuture<List<List<RiskResult>>> future = Futures.allAsList(futures); results = Futures.getUnchecked(future); finalColor = getHighestColor();//from w w w . j a v a2s .c o m hitsCount = size(nonEmptyResults(results)); groupedSelectedResults = groupByCriterionName(); LOGGER.trace("'Risk Collector' state, finalColor: {}, hitsCount: {}, groupedSelectedResults: {}", new Object[] { finalColor, hitsCount, groupedSelectedResults }); } }
From source file:org.opendaylight.openflowjava.protocol.impl.connection.SwitchConnectionProviderImpl.java
@Override public Future<List<Boolean>> shutdown() { LOGGER.debug("Shutdown summoned"); ListenableFuture<List<Boolean>> result = SettableFuture.create(); try {//from www. ja v a 2s. co m List<ListenableFuture<Boolean>> shutdownChain = new ArrayList<>(); for (ServerFacade server : serverLot) { ListenableFuture<Boolean> shutdownFuture = server.shutdown(); shutdownChain.add(shutdownFuture); } if (!shutdownChain.isEmpty()) { result = Futures.allAsList(shutdownChain); } else { throw new IllegalStateException("No servers configured"); } } catch (Exception e) { SettableFuture<List<Boolean>> exFuture = SettableFuture.create(); exFuture.setException(e); result = exFuture; } return result; }