Example usage for com.google.common.util.concurrent ListenableFuture isDone

List of usage examples for com.google.common.util.concurrent ListenableFuture isDone

Introduction

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

Prototype

boolean isDone();

Source Link

Document

Returns true if this task completed.

Usage

From source file:com.spotify.trickle.GraphExceptionWrapper.java

private static Object inputValueFromFuture(ListenableFuture<?> input) {
    if (input.isDone()) {
        return Futures.getUnchecked(input);
    } else {//from w  w w . ja va2  s .co m
        return "NOT TERMINATED FUTURE";
    }
}

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

/**
 * Create a convenience method for checking whether a future completed successfully because this
 * does not appear to be possible to do in a more direct way:
 * https://groups.google.com/forum/?fromgroups=#!topic/guava-discuss/rofEhagKnOc.
 *
 * @return true if the specified future has been resolved without throwing an exception or being
 *     cancelled.//from  w  w w. j  a  v  a  2  s  . com
 */
public static <T> boolean isSuccess(ListenableFuture<T> future) {
    if (future.isDone()) {
        try {
            future.get();
            return true;
        } catch (ExecutionException e) {
            // The computation threw an exception, so it did not complete successfully.
            return false;
        } catch (CancellationException e) {
            // The computation was cancelled, so it did not complete successfully.
            return false;
        } catch (InterruptedException e) {
            throw new RuntimeException("Should not be possible to interrupt a resolved future.", e);
        }
    } else {
        return false;
    }
}

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

/**
 * Create a convenience method for checking whether a future completed successfully because this
 * does not appear to be possible to do in a more direct way:
 * https://groups.google.com/forum/?fromgroups=#!topic/guava-discuss/rofEhagKnOc.
 *
 * @return true if the specified future has been resolved without throwing an exception or being
 *     cancelled.//from w  w w. j  a  v  a 2s.  c om
 */
public static boolean isSuccess(ListenableFuture<?> future) {
    if (!future.isDone()) {
        return false;
    }

    try {
        // Try to get the future, but ignore (and preserve) the thread interrupted state.
        // This should be fast because we know the future is already complete.
        Uninterruptibles.getUninterruptibly(future);
        return true;
    } catch (ExecutionException e) {
        // The computation threw an exception, so it did not complete successfully.
        return false;
    } catch (CancellationException e) {
        // The computation was cancelled, so it did not complete successfully.
        return false;
    }
}

From source file:io.v.v23.V23TestUtil.java

/**
 * Asserts that the given future is executed on the provided thread.
 * <p>//w  w w  .j a  va  2s.  c om
 * Note that this check is inherently racey: if the future has already completed, there is
 * no way to check on which thread it got executed.  Therefore, this method should be executed
 * as close possible to the future's creation, to reduce the chance of the race happening.
 * Additionally, the future could be created with an executor that delays execution for a time
 * period that sufficient to all but prohibit races (e.g., 100ms).
 */
public static <T> void assertRunsOnThread(ListenableFuture<T> future, final Thread thread) {
    try {
        assertThat(future.isDone()).isFalse();
        Futures.transform(future, new AsyncFunction<T, Void>() {
            @Override
            public ListenableFuture<Void> apply(T input) throws Exception {
                assertThat(Thread.currentThread()).isEqualTo(thread);
                return Futures.immediateFuture(null);
            }
        }).get();
    } catch (Exception e) {
        Truth.assertWithMessage("error asserting executor").that(e.getMessage()).isEmpty();
    }
}

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

/**
 * Returns the failure for a {@link ListenableFuture}.
 * @param future Must have completed unsuccessfully.
 *//*from   w  ww. j a v  a 2  s . co  m*/
public static Throwable getFailure(ListenableFuture<?> future) {
    Preconditions.checkArgument(future.isDone());
    Preconditions.checkArgument(!isSuccess(future));
    try {
        future.get();
        throw new IllegalStateException("get() should have thrown an exception");
    } catch (ExecutionException e) {
        return e.getCause();
    } catch (CancellationException | InterruptedException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.opendaylight.vtn.manager.internal.util.concurrent.FutureCanceller.java

/**
 * Set a future canceller that cancels the given future.
 *
 * @param timer    A {@link Timer} instance to execute the timer.
 * @param timeout  The number of milliseconds to wait for completion of
 *                 the target task.//from   w  w w.  j  a  v  a  2 s. c o m
 * @param f        A {@link ListenableFuture} instance associated with the
 *                 task to wait.
 * @param intr     {@code true} if the task runner thread should be
 *                 interrupted. Otherwise in-progress task are allowed
 *                 to complete.
 * @param <T>      The type of the result returned by the target task.
 */
public static <T> void set(Timer timer, long timeout, ListenableFuture<T> f, boolean intr) {
    if (!f.isDone()) {
        FutureCanceller<T> canceller = new FutureCanceller<T>(f, intr);
        timer.schedule(canceller, timeout);
        Futures.addCallback(f, canceller);
    }
}

From source file:dagger.functional.producers.cancellation.CancellationModule.java

@Produces
@Named("ep3")// www. java 2 s . com
static ListenableFuture<String> produceEntryPoint3(Producer<String> dependencyProducer) {
    ListenableFuture<String> dependencyFuture = dependencyProducer.get();
    assertThat(dependencyFuture.isDone()).isFalse();
    assertThat(dependencyFuture.cancel(true)).isTrue();
    assertThat(dependencyFuture.isCancelled()).isTrue();
    return dependencyFuture;
}

From source file:io.prestosql.execution.buffer.BufferTestUtils.java

static ListenableFuture<?> enqueuePage(OutputBuffer buffer, Page page) {
    buffer.enqueue(ImmutableList.of(PAGES_SERDE.serialize(page)));
    ListenableFuture<?> future = buffer.isFull();
    assertFalse(future.isDone());
    return future;
}

From source file:io.prestosql.execution.buffer.BufferTestUtils.java

static ListenableFuture<?> enqueuePage(OutputBuffer buffer, Page page, int partition) {
    buffer.enqueue(partition, ImmutableList.of(PAGES_SERDE.serialize(page)));
    ListenableFuture<?> future = buffer.isFull();
    assertFalse(future.isDone());
    return future;
}

From source file:com.facebook.buck.distributed.build_client.RacingBuildPhase.java

/**
 * Races local build against distributed build, returning when either: - Local racing build
 * finishes before distributed build - 'Most build rules finished' event received - Distributed
 * build failed. -- If local fallback mode is enabled, waits for racing build to finish before
 * returning.//  w w  w  .j  av a2s  .com
 *
 * @return True if all work completed during this phase and further phases not necessary
 * @throws InterruptedException
 */
public static boolean run(DistBuildRunner distBuildRunner, LocalBuildRunner racingBuildRunner,
        RemoteBuildRuleCompletionWaiter remoteBuildRuleCompletionWaiter, boolean localBuildFallbackEnabled,
        BuckEventBus eventBus) throws InterruptedException {
    LOG.info("Starting racing build phase.");
    eventBus.post(new StampedeLocalBuildStatusEvent("racing"));

    racingBuildRunner.runLocalBuildAsync();
    attachMostBuildRulesCompletedCallback(racingBuildRunner, remoteBuildRuleCompletionWaiter);

    LOG.info("Waiting for racing build to finish, or most build rules event to be received..");
    racingBuildRunner.getBuildPhaseLatch().await();

    boolean mostBuildRulesFinishedInFailure = false;
    ListenableFuture<Boolean> mostBuildRulesFinished = remoteBuildRuleCompletionWaiter
            .waitForMostBuildRulesToFinishRemotely();
    if (mostBuildRulesFinished.isDone()) {
        try {
            mostBuildRulesFinishedInFailure = !mostBuildRulesFinished.get();
        } catch (ExecutionException e) {
            mostBuildRulesFinishedInFailure = true;
        }
    }

    if (racingBuildRunner.isFinished()) {
        LOG.info("Local racing build finished before distributed build.");
        distBuildRunner.cancelAsLocalBuildFinished(racingBuildRunner.finishedSuccessfully(),
                racingBuildRunner.getExitCode());
        return true; // Build is done. Nothing more to do
    } else if (distBuildRunner.finishedSuccessfully()) {
        // Distributed build finished without a 'most build rules finished' event.
        // Technically this shouldn't happen, but handle it gracefully anyway.
        String message = "Distributed build finished before local racing build. Moving to synchronized build phase.";
        LOG.warn(message);
        racingBuildRunner.cancelAndWait(message);
        return false;
    } else if (distBuildRunner.failed() || mostBuildRulesFinishedInFailure) {
        LOG.info("Distributed build failed before local racing build.");
        if (localBuildFallbackEnabled) {
            // Wait for local build to finish, no need to execute sync build.
            // TODO(alisdair, shivanker): It _might_ be better to switch to synchronized build here.
            // The trade-off is that synchronized build would waste time in restarting the build
            // (computing rule-keys, parsing the tree - to get local key unchanged hits, etc.) but
            // it could probably get cache hits on some top-level artifacts, which would save time
            // against the racing build which is going to download all lower level artifacts in case it
            // already expanded that top-level node.
            eventBus.post(new StampedeLocalBuildStatusEvent("fallback", "Local Build"));
            LOG.info("Falling back to local racing build. Waiting for it to finish..");
            racingBuildRunner.waitUntilFinished();
        } else {
            // Kill local build, no need to execute sync build.
            LOG.info("Killing local racing build as local fallback not enabled.");
            racingBuildRunner.cancelAndWait("Distributed build failed, and local fallback not enabled.");
        }

        return true;
    } else if (mostBuildRulesFinished.isDone()) {
        // Important: this is the most generic case (as finishing a dist build will unlock this future
        // too), so ensure that it comes last in the if/else clauses.
        String message = "Most build rules finished remotely before local racing build. Moving to synchronized build phase.";
        LOG.info(message);
        racingBuildRunner.cancelAndWait(message);
        return false;
    }

    LOG.error("Unsupported code path hit in racing build phase. Assuming it failed.");
    return false;
}