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

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

Introduction

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

Prototype

@Beta
@GwtIncompatible("TODO")
@CheckReturnValue
public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(
        Iterable<? extends ListenableFuture<? extends T>> futures) 

Source Link

Document

Returns a list of delegate futures that correspond to the futures received in the order that they complete.

Usage

From source file:monasca.persister.repository.cassandra.CassandraRepo.java

public int handleFlush(String id) throws RepoException {
    long startTime = System.nanoTime();

    int flushedCount = 0;
    List<ResultSetFuture> results = new ArrayList<>(queue.size());
    Statement query;/*from w  ww  .  j a  v  a 2s  .  c  om*/
    while ((query = queue.poll()) != null) {
        flushedCount++;
        results.add(session.executeAsync(query));
    }

    List<ListenableFuture<ResultSet>> futures = Futures.inCompletionOrder(results);

    boolean cancel = false;
    Exception ex = null;
    for (ListenableFuture<ResultSet> future : futures) {
        if (cancel) {
            future.cancel(false);
            continue;
        }
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            cancel = true;
            ex = e;
        }
    }

    commitTimer.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);

    if (ex != null) {
        throw new RepoException(ex);
    }
    return flushedCount;
}

From source file:diskCacheV111.srm.dcache.DcacheSrm.java

private <T extends Serializable> List<ListenableFuture<T>> queryRemotes(Serializable request,
        Class<T> response) {
    return Futures.inCompletionOrder(backends.getCurrentData().stream().map(this::toCellAddress)
            .filter(adr -> !address.equals(adr)).map(CellPath::new)
            .map(path -> srmManagerStub.send(path, request, response)).collect(toList()));
}

From source file:org.sosy_lab.cpachecker.core.algorithm.ParallelAlgorithm.java

private void handleFutureResults(List<ListenableFuture<ParallelAnalysisResult>> futures)
        throws InterruptedException, Error, CPAException {

    List<CPAException> exceptions = new ArrayList<>();
    for (ListenableFuture<ParallelAnalysisResult> f : Futures.inCompletionOrder(futures)) {
        try {/* ww  w .  j  av  a2s.  c  o m*/
            ParallelAnalysisResult result = f.get();
            if (result.hasValidReachedSet() && finalResult == null) {
                finalResult = result;
                stats.successfulAnalysisName = result.getAnalysisName();

                // cancel other computations
                futures.forEach(future -> future.cancel(true));
                logger.log(Level.INFO, result.getAnalysisName() + " finished successfully.");
                shutdownManager.requestShutdown(SUCCESS_MESSAGE);
            } else if (!result.hasValidReachedSet()) {
                logger.log(Level.INFO, result.getAnalysisName() + " finished without usable result.");
            }
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof CPAException) {
                if (cause.getMessage().contains("recursion")) {
                    logger.logUserException(Level.WARNING, cause, "Analysis not completed due to recursion");
                }
                if (cause.getMessage().contains("pthread_create")) {
                    logger.logUserException(Level.WARNING, cause, "Analysis not completed due to concurrency");
                }
                exceptions.add((CPAException) cause);

            } else {
                // cancel other computations
                futures.forEach(future -> future.cancel(true));
                shutdownManager.requestShutdown("cancelling all remaining analyses");
                throw new CPAException("An unexpected exception occured", cause);
            }
        } catch (CancellationException e) {
            // do nothing, this is normal if we cancel other analyses
        }
    }

    // we do not have any result, so we propagate the found CPAExceptions upwards
    if (finalResult == null && !exceptions.isEmpty()) {
        if (exceptions.size() == 1) {
            throw Iterables.getOnlyElement(exceptions);
        } else {
            throw new CompoundException("Several exceptions occured during the analysis", exceptions);
        }
    }
}

From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java

/**
 * Leverages the token-awareness of the driver to optimally query each node directly instead of invoking a
 * coordinator node. Sends an individual query for each partition key, so reaches the appropriate replica
 * directly and collates the results client-side.
 * //  w ww  . j a va2  s. c o m
 * @param ids the partition keys (identifiers) to select.
 * @return a List of ListenableFuture instances for each underlying ResultSet--one for each ID.
 */
private List<ListenableFuture<ResultSet>> submitReadIn(Identifier... ids) {
    if (ids == null)
        return Collections.emptyList();

    List<ResultSetFuture> futures = new ArrayList<ResultSetFuture>(ids.length);

    for (Identifier id : ids) {
        BoundStatement bs = new BoundStatement(statementFactory.read());
        bindIdentity(bs, id);
        futures.add(session.executeAsync(bs));
    }

    return Futures.inCompletionOrder(futures);
}

From source file:monasca.persister.repository.cassandra.CassandraMetricRepo.java

@Override
public int flush(String id) throws RepoException {
    long startTime = System.nanoTime();
    List<ResultSetFuture> results = new ArrayList<>();
    List<Deque<BatchStatement>> list = batches.getAllBatches();
    for (Deque<BatchStatement> q : list) {
        BatchStatement b;// w ww  .  ja  va2  s  . co  m
        while ((b = q.poll()) != null) {
            results.add(session.executeAsync(b));
        }
    }

    List<ListenableFuture<ResultSet>> futures = Futures.inCompletionOrder(results);

    boolean cancel = false;
    Exception ex = null;
    for (ListenableFuture<ResultSet> future : futures) {
        if (cancel) {
            future.cancel(false);
            continue;
        }
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            cancel = true;
            ex = e;
        }
    }

    this.commitTimer.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);

    if (ex != null) {
        metricFailed.inc(metricCount);
        throw new RepoException(ex);
    }

    batches.clear();
    int flushCnt = metricCount;
    metricCount = 0;
    metricCompleted.inc(flushCnt);
    return flushCnt;
}