Example usage for com.google.common.util.concurrent Futures allAsList

List of usage examples for com.google.common.util.concurrent Futures allAsList

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures allAsList.

Prototype

@Beta
@CheckReturnValue
public static <V> ListenableFuture<List<V>> allAsList(
        Iterable<? extends ListenableFuture<? extends V>> futures) 

Source Link

Document

Creates a new ListenableFuture whose value is a list containing the values of all its input futures, if all succeed.

Usage

From source file:com.google.javascript.jscomp.PrebuildDependencyInfo.java

void prebuild(Iterable<CompilerInput> allInputs) {
    ThreadFactory threadFactory = new ThreadFactory() {
        @Override/*  w w  w.  j  a va2  s. c o  m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(null, r, "jscompiler-PrebuildDependencyInfo",
                    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.getDependencyInfo();
            }
        }));
    }

    poolExecutor.shutdown();
    try {
        Futures.allAsList(futureList).get();
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:dagger.producers.internal.Producers.java

/**
 * Creates a new {@code ListenableFuture} whose value is a set containing the values of all its
 * input futures, if all succeed. If any input fails, the returned future fails immediately.
 *
 * <p>This is the set equivalent of {@link Futures#allAsList}.
 *///from   w w w .  ja  v a2  s  .  co  m
public static <T> ListenableFuture<Set<T>> allAsSet(Iterable<? extends ListenableFuture<? extends T>> futures) {
    return transform(Futures.allAsList(futures), new Function<List<T>, Set<T>>() {
        @Override
        public Set<T> apply(List<T> values) {
            return ImmutableSet.copyOf(values);
        }
    }, directExecutor());
}

From source file:com.facebook.buck.parser.ConvertingPipeline.java

@Override
public ListenableFuture<ImmutableSet<T>> getAllNodesJob(final Cell cell, final Path buildFile)
        throws BuildTargetException {
    // TODO(csarbora): this hits the chained pipeline before hitting the cache
    ListenableFuture<List<T>> allNodesListJob = Futures.transformAsync(getItemsToConvert(cell, buildFile),
            allToConvert -> {// w  ww  .j  a v  a 2s  .c o  m
                if (shuttingDown()) {
                    return Futures.immediateCancelledFuture();
                }

                ImmutableList.Builder<ListenableFuture<T>> allNodeJobs = ImmutableList.builder();

                for (final F from : allToConvert) {
                    if (isValid(from)) {
                        final BuildTarget target = getBuildTarget(cell.getRoot(), buildFile, from);
                        allNodeJobs.add(cache.getJobWithCacheLookup(cell, target, () -> {
                            if (shuttingDown()) {
                                return Futures.immediateCancelledFuture();
                            }
                            return dispatchComputeNode(cell, target, from);
                        }));
                    }
                }

                return Futures.allAsList(allNodeJobs.build());
            }, executorService);
    return Futures.transform(allNodesListJob, (Function<List<T>, ImmutableSet<T>>) ImmutableSet::copyOf,
            executorService);
}

From source file:dagger.producers.internal.MapOfProducedProducer.java

@Override
public ListenableFuture<Map<K, Produced<V>>> compute() {
    return Futures.transformAsync(mapProducerProducer.get(),
            new AsyncFunction<Map<K, Producer<V>>, Map<K, Produced<V>>>() {
                @Override/* w  w w .  j  a va 2s.com*/
                public ListenableFuture<Map<K, Produced<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(),
                                    MapOfProducedProducer.<K, V>entryUnwrapper())),
                            new Function<List<Map.Entry<K, Produced<V>>>, Map<K, Produced<V>>>() {
                                @Override
                                public Map<K, Produced<V>> apply(List<Map.Entry<K, Produced<V>>> entries) {
                                    return ImmutableMap.copyOf(entries);
                                }
                            }, directExecutor());
                }
            }, directExecutor());
}

From source file:com.google.idea.blaze.android.sync.importer.problems.GeneratedResourceClassifier.java

GeneratedResourceClassifier(Collection<ArtifactLocation> generatedResourceLocations,
        ArtifactLocationDecoder artifactLocationDecoder, ListeningExecutorService executorService) {
    FileAttributeProvider fileAttributeProvider = FileAttributeProvider.getInstance();
    List<ListenableFuture<GenResourceClassification>> jobs = generatedResourceLocations.stream()
            .map(location -> executorService
                    .submit(() -> classifyLocation(location, artifactLocationDecoder, fileAttributeProvider)))
            .collect(Collectors.toList());

    ImmutableSortedMap.Builder<ArtifactLocation, Integer> interesting = ImmutableSortedMap.naturalOrder();
    try {//  w w  w .j av a 2s  .c  o m
        for (GenResourceClassification classification : Futures.allAsList(jobs).get()) {
            if (classification.isInteresting) {
                interesting.put(classification.artifactLocation, classification.numSubDirs);
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        interesting = considerAllInteresting(generatedResourceLocations);
    } catch (ExecutionException e) {
        logger.error(e);
        interesting = considerAllInteresting(generatedResourceLocations);
    } finally {
        interestingDirectories = interesting.build();
    }
}

From source file:com.google.devtools.build.lib.remote.ByteStreamBuildEventArtifactUploader.java

@Override
public ListenableFuture<PathConverter> upload(Map<Path, LocalFile> files) {
    if (files.isEmpty()) {
        return Futures.immediateFuture(PathConverter.NO_CONVERSION);
    }//from   w w  w . j  a  v a 2s . co m
    List<ListenableFuture<PathDigestPair>> uploads = new ArrayList<>(files.size());

    Context prevCtx = ctx.attach();
    try {
        for (Path file : files.keySet()) {
            Chunker chunker = new Chunker(file);
            Digest digest = chunker.digest();
            ListenableFuture<PathDigestPair> upload = Futures.transform(
                    uploader.uploadBlobAsync(chunker, /*forceUpload=*/false),
                    unused -> new PathDigestPair(file, digest), MoreExecutors.directExecutor());
            uploads.add(upload);
        }

        return Futures.transform(Futures.allAsList(uploads),
                (uploadsDone) -> new PathConverterImpl(remoteServerInstanceName, uploadsDone),
                MoreExecutors.directExecutor());
    } catch (IOException e) {
        return Futures.immediateFailedFuture(e);
    } finally {
        ctx.detach(prevCtx);
    }
}

From source file:com.abiquo.bond.api.EventDispatcher.java

/**
 * Submits a Future to the ExecutorService that will execute the plugin's processEvent method
 * for the event. Also creates a callback that will be executed when all the plugins have
 * completed processing the event. The callback method updates the lastEventTimestamp variable.
 * /*from w  ww  .j  a  va2  s. c  o  m*/
 * @param event the event to be processed by each plugin
 */
void dispatchEvent(final APIEvent event) {
    List<ListenableFuture<APIEventResult>> futures = new ArrayList<>();
    for (final PluginInterface plugin : plugins) {
        if (plugin.handlesEventType(event.getClass())) {
            ListenableFuture<APIEventResult> task = eventDispatcher.submit(() -> plugin.processEvent(event));
            futures.add(task);
        }
    }

    if (!futures.isEmpty()) {
        Futures.addCallback(Futures.allAsList(futures), new FutureCallback<List<APIEventResult>>() {

            @Override
            public void onSuccess(final List<APIEventResult> results) {
                for (APIEventResult result : results) {
                    LocalDateTime eventTs = result.getEvent().getTimestamp();
                    if (lastEventTimestamp == null || lastEventTimestamp.isBefore(eventTs)) {
                        lastEventTimestamp = eventTs;
                        logger.info("Last event timestamp updated to {}", lastEventTimestamp);
                    }
                }

            }

            @Override
            public void onFailure(final Throwable t) {
                if (t instanceof PluginEventException) {
                    PluginEventException pee = (PluginEventException) t;
                    Optional<APIEvent> optEvent = pee.getAPIEvent();
                    if (optEvent.isPresent()) {
                        LocalDateTime eventts = optEvent.get().getTimestamp();
                        if (lastEventTimestamp == null || lastEventTimestamp.isBefore(eventts)) {
                            lastEventTimestamp = eventts;
                        }
                    }
                } else {
                    // There's nothing we can do if any other exception type is thrown as we
                    // won't know which event was being processed. Simply log a message.
                    // Hopefully one of the other plugins will process the event
                    // successfully and that will update the timestamp. If not then the
                    // event will be resubmitted for processing by all plugins if no later
                    // events are successfully processed.
                    logger.error("Processing of event failed", t);
                }
            }
        });
    }
}

From source file:org.thingsboard.server.dao.attributes.BaseAttributesDao.java

@Override
public ListenableFuture<List<AttributeKvEntry>> find(EntityId entityId, String attributeType,
        Collection<String> attributeKeys) {
    List<ListenableFuture<Optional<AttributeKvEntry>>> entries = new ArrayList<>();
    attributeKeys.forEach(attributeKey -> entries.add(find(entityId, attributeType, attributeKey)));
    return Futures.transform(Futures.allAsList(entries),
            (Function<List<Optional<AttributeKvEntry>>, ? extends List<AttributeKvEntry>>) input -> {
                List<AttributeKvEntry> result = new ArrayList<>();
                input.stream().filter(opt -> opt.isPresent()).forEach(opt -> result.add(opt.get()));
                return result;
            }, readResultsProcessingExecutor);
}

From source file:org.opendaylight.netconf.topology.impl.OnlySuccessStateAggregator.java

@Override
public ListenableFuture<Void> combineDeleteAttempts(List<ListenableFuture<Void>> stateFutures) {
    final SettableFuture<Void> future = SettableFuture.create();
    final ListenableFuture<List<Void>> allAsList = Futures.allAsList(stateFutures);
    Futures.addCallback(allAsList, new FutureCallback<List<Void>>() {
        @Override//  w w  w  .  j a va  2  s .  c o m
        public void onSuccess(List<Void> result) {
            future.set(null);
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("One of the combined delete attempts failed {}", t);
            future.setException(t);
        }
    });
    return future;
}

From source file:com.google.pubsub.flic.controllers.Controller.java

/**
 * Waits for clients to complete the load test.
 *///from   w ww .j a  v a2  s  .co  m
public void waitForClients() throws Throwable {
    try {
        Futures.allAsList(clients.stream().map(Client::getDoneFuture).collect(Collectors.toList())).get();
    } catch (ExecutionException e) {
        throw e.getCause();
    }
}