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.spotify.folsom.LoadTestRunner.java

public static void main(final String[] args) throws Throwable {
    final BinaryMemcacheClient<String> client = new MemcacheClientBuilder<>(StringTranscoder.UTF8_INSTANCE)
            .withAddress("127.0.0.1").withMaxOutstandingRequests(100000).connectBinary();

    final String[] keys = new String[10];
    for (int i = 0; i < 10; i++) {
        keys[i] = "key" + i;
    }//w  w w . j a  va2s.c o m

    final List<ListenableFuture<Boolean>> futures = Lists.newArrayList();
    for (int r = 0; r < 100; r++) {
        for (final String keyProto : keys) {
            final String key = keyProto + ":" + r;

            final ListenableFuture<MemcacheStatus> setFuture = client.set(key, "value" + key, 100000);
            final ListenableFuture<String> getFuture = Utils.transform(setFuture,
                    new AsyncFunction<MemcacheStatus, String>() {
                        @Override
                        public ListenableFuture<String> apply(final MemcacheStatus input) throws Exception {
                            return client.get(key);
                        }
                    });
            final ListenableFuture<String> deleteFuture = Utils.transform(getFuture,
                    new AsyncFunction<String, String>() {
                        @Override
                        public ListenableFuture<String> apply(final String value) throws Exception {
                            return Utils.transform(client.delete(key), new Function<MemcacheStatus, String>() {
                                @Override
                                public String apply(final MemcacheStatus input) {
                                    return value;
                                }
                            });
                        }
                    });

            final ListenableFuture<Boolean> assertFuture = Utils.transform(deleteFuture,
                    new Function<String, Boolean>() {
                        @Override
                        public Boolean apply(final String input) {
                            return ("value" + key).equals(input);
                        }
                    });

            futures.add(assertFuture);
        }
    }

    final List<Boolean> asserts = Futures.allAsList(futures).get();

    int failed = 0;
    for (final boolean b : asserts) {
        if (!b) {
            failed++;
        }
    }
    System.out.println(failed + " failed of " + asserts.size());

    client.shutdown();
}

From source file:com.google.idea.blaze.base.io.FileAttributeScanner.java

public static <T> ImmutableMap<File, T> readAttributes(Iterable<File> fileList,
        AttributeReader<T> attributeReader, BlazeExecutor executor) throws Exception {
    List<ListenableFuture<FilePair<T>>> futures = Lists.newArrayList();
    for (File file : fileList) {
        futures.add(executor.submit(() -> {
            T attribute = attributeReader.getAttribute(file);
            if (attributeReader.isValid(attribute)) {
                return new FilePair<>(file, attribute);
            }/*from  ww w  . ja v a2 s. c o m*/
            return null;
        }));
    }

    ImmutableMap.Builder<File, T> result = ImmutableMap.builder();
    for (FilePair<T> filePair : Futures.allAsList(futures).get()) {
        if (filePair != null) {
            result.put(filePair.file, filePair.attribute);
        }
    }
    return result.build();
}

From source file:com.facebook.buck.rules.Builder.java

public ListenableFuture<List<BuildRuleSuccess>> buildRules(final BuildEngine buildEngine,
        Iterable<BuildRule> rules, final BuildContext context) {
    return Futures.allAsList(
            Iterables.transform(rules, new Function<BuildRule, ListenableFuture<BuildRuleSuccess>>() {
                @Override/*from w ww. ja v a 2  s  . com*/
                public ListenableFuture<BuildRuleSuccess> apply(BuildRule rule) {
                    return buildEngine.build(context, rule);
                }
            }));
}

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

@Override
public ListenableFuture<Node> combineCreateAttempts(List<ListenableFuture<Node>> stateFutures) {
    final SettableFuture<Node> future = SettableFuture.create();
    final ListenableFuture<List<Node>> allAsList = Futures.allAsList(stateFutures);
    Futures.addCallback(allAsList, new FutureCallback<List<Node>>() {
        @Override/*  w w  w. jav a 2s.c om*/
        public void onSuccess(List<Node> result) {
            for (int i = 0; i < result.size() - 1; i++) {
                if (!result.get(i).equals(result.get(i + 1))) {
                    future.setException(new IllegalStateException("Create futures have different result"));
                }
            }
            future.set(result.get(0));
        }

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

    return future;
}

From source file:com.spotify.scio.extra.transforms.GuavaAsyncDoFn.java

@Override
protected void waitForFutures(Iterable<ListenableFuture<OutputT>> futures)
        throws InterruptedException, ExecutionException {
    Futures.allAsList(futures).get();
}

From source file:com.facebook.buck.util.concurrent.MoreFutures.java

/**
 * Invoke multiple callables on the provided executor and wait for all to return successfully.
 * An exception is thrown (immediately) if any callable fails.
 * @param executorService Executor service.
 * @param callables Callables to call.// w  w w.  j av a2  s.  c  o  m
 * @return List of values from each invoked callable in order if all callables execute without
 *     throwing.
 * @throws ExecutionException If any callable throws an exception, the first of such is wrapped
 *     in an ExecutionException and thrown.  Access via
 *     {@link java.util.concurrent.ExecutionException#getCause()}}.
 */
public static <V> List<V> getAllUninterruptibly(ListeningExecutorService executorService,
        Iterable<Callable<V>> callables) throws ExecutionException {
    // Invoke.
    ImmutableList.Builder<ListenableFuture<V>> futures = ImmutableList.builder();
    for (Callable<V> callable : callables) {
        ListenableFuture<V> future = executorService.submit(callable);
        futures.add(future);
    }

    // Wait for completion.
    ListenableFuture<List<V>> allAsOne = Futures.allAsList(futures.build());
    return Uninterruptibles.getUninterruptibly(allAsOne);
}

From source file:org.immutables.eventual.CompletedModule.java

static ListenableFuture<Module> from(Injector injectingFutures, CompletionCriteria criteria) {
    final LinkedHashMap<Key<?>, Key<?>> keyMapping = mapUnfutureKeys(injectingFutures);
    List<ListenableFuture<?>> listOfFutures = getFutureInstances(keyMapping.keySet(), injectingFutures);

    ListenableFuture<List<Object>> futureOfList = criteria == CompletionCriteria.SUCCESSFUL
            ? Futures.successfulAsList(listOfFutures)
            : Futures.allAsList(listOfFutures);

    return Futures.transform(futureOfList, new Function<List<Object>, Module>() {
        Key<?>[] keys = Iterables.toArray(keyMapping.values(), Key.class);

        @Override/*from  w  ww. j  a  v  a  2  s. c  o m*/
        public Module apply(List<Object> instances) {
            return new CompletedModule(keys, instances.toArray());
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.facebook.buck.distributed.RuleKeyUtils.java

/**
 * Calculates default rule keys for nodes in given graph
 *
 * @return Map of rules to their keys/*www.j ava  2 s . c o  m*/
 */
public static ListenableFuture<List<Pair<BuildRule, RuleKey>>> calculateDefaultRuleKeys(
        ActionGraphBuilder actionGraphBuilder, ParallelRuleKeyCalculator<RuleKey> ruleKeyCalculator,
        BuckEventBus eventBus, Iterable<BuildTarget> topLevelTargets) {
    Set<BuildRule> allRulesInGraph = findAllRulesInGraph(topLevelTargets, actionGraphBuilder);

    List<ListenableFuture<Pair<BuildRule, RuleKey>>> ruleKeys = new ArrayList<>(allRulesInGraph.size());
    for (BuildRule rule : allRulesInGraph) {
        ruleKeys.add(Futures.transform(ruleKeyCalculator.calculate(eventBus, rule), ruleKey -> {
            LOG.debug("Rule key calculation: [%s] [%s]", rule.getFullyQualifiedName(), ruleKey);
            return new Pair<>(rule, ruleKey);
        }, MoreExecutors.directExecutor()));
    }

    return Futures.allAsList(ruleKeys);
}

From source file:org.robotninjas.concurrent.FluentFutures.java

/**
 *
 * @param futures//from   w  w w.ja va2 s.com
 * @param <Y>
 * @return
 */
@SafeVarargs
public static <Y> FluentFuture<List<Y>> from(ListenableFuture<Y>... futures) {
    return new FluentDecorator<>(Futures.allAsList(Arrays.asList(futures)));
}

From source file:org.apache.hadoop.hbase.index.parallel.QuickFailingTaskRunner.java

@Override
protected <R> ListenableFuture<List<R>> submitTasks(List<ListenableFuture<R>> futures) {
    return Futures.allAsList(futures);
}