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

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

Introduction

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

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:com.google.devtools.build.lib.concurrent.MoreFutures.java

/**
 * Creates a new {@code ListenableFuture} whose value is a list containing the
 * values of all its input futures, if all succeed. If any input fails, the
 * returned future fails. If any of the futures fails, it cancels all the other futures.
 *
 * <p> This method is similar to {@code Futures.allAsList} but additionally it cancels all the
 * futures in case any of them fails.//from   w w  w  .j  a va 2  s. co  m
 */
public static <V> ListenableFuture<List<V>> allAsListOrCancelAll(
        final Iterable<? extends ListenableFuture<? extends V>> futures) {
    ListenableFuture<List<V>> combinedFuture = Futures.allAsList(futures);
    Futures.addCallback(combinedFuture, new FutureCallback<List<V>>() {
        @Override
        public void onSuccess(@Nullable List<V> vs) {
        }

        /**
         * In case of a failure of any of the futures (that gets propagated to combinedFuture) we
         * cancel all the futures in the list.
         */
        @Override
        public void onFailure(Throwable ignore) {
            for (ListenableFuture<? extends V> future : futures) {
                future.cancel(true);
            }
        }
    });
    return combinedFuture;
}

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

@Produces
@Named("ep3")//from w ww  . j  av  a  2 s .c  o  m
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:com.facebook.presto.execution.scheduler.NodeScheduler.java

private static ListenableFuture<?> getFirstCompleteAndCancelOthers(List<ListenableFuture<?>> blockedFutures) {
    // wait for the first task to unblock and then cancel all futures to free up resources
    ListenableFuture<?> result = whenAnyComplete(blockedFutures);
    result.addListener(() -> {//from w ww  .  j  a  va2 s .com
        for (ListenableFuture<?> blockedFuture : blockedFutures) {
            blockedFuture.cancel(true);
        }
    }, MoreExecutors.directExecutor());
    return result;
}

From source file:org.dcache.util.CompletableFutures.java

/**
 * Create a CompletableFuture from guava's ListenableFuture to
 * help migration from Guava to Java8.//from  w ww. jav  a 2s.c o  m
 * @param listenable ListenableFuture to convert.
 * @return new CompletableFuture.
 */
public static <T> CompletableFuture<T> fromListenableFuture(ListenableFuture<T> listenable) {

    final CompletableFuture<T> completable = new CompletableFuture<T>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            // propagate cancel to the listenable future
            boolean result = listenable.cancel(mayInterruptIfRunning);
            super.cancel(mayInterruptIfRunning);
            return result;
        }
    };

    // propagate results to completable future
    Futures.addCallback(listenable, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            completable.complete(result);
        }

        @Override
        public void onFailure(Throwable t) {
            completable.completeExceptionally(t);
        }
    }, MoreExecutors.directExecutor());
    return completable;
}

From source file:org.opendaylight.sfc.genius.impl.utils.SfcGeniusUtils.java

/**
 * Adapts a {@link ListenableFuture} to a {@link CompletableFuture}. The
 * provided executor is used to execute the callback as per
 * {@link Futures#addCallback(ListenableFuture, FutureCallback, Executor)}
 * On such callback, completion will be performed.
 *
 * @param listenableFuture/*from   w w w  . j av a2s.co  m*/
 *            the listenable future to adapt.
 * @param executor
 *            the executor where the callback execution is submitted.
 * @param <T>
 *            the type of the listenable future.
 * @return the completable future.
 */
public static <T> CompletableFuture<T> toCompletableFuture(final ListenableFuture<T> listenableFuture,
        Executor executor) {

    CompletableFuture<T> completable = new CompletableFuture<T>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            boolean result = listenableFuture.cancel(mayInterruptIfRunning);
            super.cancel(mayInterruptIfRunning);
            return result;
        }
    };

    Futures.addCallback(listenableFuture, new FutureCallback<T>() {
        @Override
        public void onSuccess(@Nullable T listenable) {
            completable.complete(listenable);
        }

        @Override
        public void onFailure(Throwable throwable) {
            completable.completeExceptionally(throwable);
        }
    }, executor);
    return completable;
}

From source file:com.torodb.common.util.ListeningFutureToCompletableFuture.java

public static <T> CompletableFuture<T> toCompletableFuture(final ListenableFuture<T> listenableFuture) {
    //create an instance of CompletableFuture
    CompletableFuture<T> completable = new CompletableFuture<T>() {
        @Override// w  w w .j  ava 2 s .c o m
        public boolean cancel(boolean mayInterruptIfRunning) {
            // propagate cancel to the listenable future
            boolean result = listenableFuture.cancel(mayInterruptIfRunning);
            super.cancel(mayInterruptIfRunning);
            return result;
        }
    };

    // add callback
    Futures.addCallback(listenableFuture, new FutureCallback<T>() {
        @Override
        @SuppressFBWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE")
        public void onSuccess(T result) {
            completable.complete(result);
        }

        @Override
        public void onFailure(Throwable t) {
            completable.completeExceptionally(t);
        }
    });
    return completable;
}

From source file:com.spotify.heroic.metric.datastax.Async.java

/**
 * Helper method to convert a {@link ListenableFuture} to an {@link AsyncFuture}.
 *//*from   w  w w . jav  a 2  s.  com*/
public static <T> AsyncFuture<T> bind(AsyncFramework async, ListenableFuture<T> source) {
    final ResolvableFuture<T> target = async.future();

    Futures.addCallback(source, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            target.resolve(result);
        }

        @Override
        public void onFailure(Throwable t) {
            target.fail(t);
        }
    });

    target.onCancelled(() -> {
        source.cancel(false);
    });

    return target;
}

From source file:com.google.idea.blaze.base.async.executor.BlazeExecutor.java

public static ListenableFuture<Void> submitTask(@Nullable final Project project, @NotNull final String title,
        final boolean cancelable, final Modality modality, @NotNull final Progressive progressive) {

    // The progress indicator must be created on the UI thread.
    final ProgressWindow indicator = UIUtil.invokeAndWaitIfNeeded(new Computable<ProgressWindow>() {
        @Override/* ww w  . ja  v a2s .  c  o  m*/
        public ProgressWindow compute() {
            if (modality == Modality.MODAL) {
                ProgressWindow indicator = new ProgressWindow(cancelable, project);
                indicator.setTitle(title);
                return indicator;
            } else {
                PerformInBackgroundOption backgroundOption = modality == Modality.BACKGROUNDABLE
                        ? PerformInBackgroundOption.DEAF
                        : PerformInBackgroundOption.ALWAYS_BACKGROUND;
                return new BackgroundableProcessIndicator(project, title, backgroundOption, "Cancel", "Cancel",
                        cancelable);
            }
        }
    });

    indicator.setIndeterminate(true);
    indicator.start();
    final Runnable process = new Runnable() {
        @Override
        public void run() {
            progressive.run(indicator);
        }
    };
    final ListenableFuture<Void> future = getInstance().submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            ProgressManager.getInstance().runProcess(process, indicator);
            return null;
        }
    });
    if (cancelable) {
        indicator.addStateDelegate(new AbstractProgressIndicatorExBase() {
            @Override
            public void cancel() {
                super.cancel();
                future.cancel(true);
            }
        });
    }
    return future;
}

From source file:com.salesforce.grpc.contrib.MoreFutures.java

/**
 * Converts a Guava {@link ListenableFuture} into a JDK {@link CompletableFuture}, preserving value, exception,
 * and cancellation propagation./*from   w  w w  . j a v  a  2  s  .com*/
 *
 * <p>The resulting {@link CompletableFuture} acts on the same {@link Executor} as the provided {@link ListenableFuture}.
 * @param listenableFuture A {@link ListenableFuture} to adapt.
 * @return A new {@link CompletableFuture}.
 */
public static <V> CompletableFuture<V> toCompletableFuture(
        @Nonnull final ListenableFuture<V> listenableFuture) {
    checkNotNull(listenableFuture, "listenableFuture");

    // Setup backward cancellation propagation CF -> LF
    final CompletableFuture<V> completableFuture = new CompletableFuture<V>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return super.cancel(mayInterruptIfRunning) && listenableFuture.cancel(mayInterruptIfRunning);
        }

        // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
        // CompletableFuture.cancel(bool) is the same as CompleteExceptionally(new CancellationException())
        @Override
        public boolean completeExceptionally(Throwable ex) {
            if (ex instanceof CancellationException) {
                listenableFuture.cancel(true);
            }
            return super.completeExceptionally(ex);
        }
    };

    // Setup forward event propagation LF -> CF
    Runnable callbackRunnable = () -> {
        try {
            final V value = listenableFuture.get();
            completableFuture.complete(value);
        } catch (CancellationException ex) { // the ListenableFuture was cancelled
            completableFuture.cancel(true);
        } catch (ExecutionException ex) { // the ListenableFuture failed with a exception
            completableFuture.completeExceptionally(ex.getCause());
        } catch (RuntimeException | Error ex) { // the ListenableFuture failed with a REALLY BAD exception
            completableFuture.completeExceptionally(ex);
        } catch (InterruptedException ex) {
            completableFuture.completeExceptionally(ex); // Won't happen since get() only called after completion
        }
    };
    listenableFuture.addListener(callbackRunnable, MoreExecutors.directExecutor());

    return completableFuture;
}

From source file:com.spotify.futures.FuturesExtra.java

/**
 * This takes two futures of type {@link A} and {@link B} and works like
 * a valve on {@link A}, with validation executed on {@link B}.
 *
 * Returns a future with the result of {@link A} that will wait for a
 * condition on {@link B} to be validated first. Both futures can run in
 * parallel. If the condition fails validation, the {@link A} future will
 * be cancelled by a call to {@link ListenableFuture#cancel(boolean)} with
 * {@code false}.//  ww  w .j a v a 2 s.  co  m
 *
 * This is useful for when you want to optimistically run a time consuming
 * path while validating if it should be computed or not by a parallel
 * async computation.
 *
 * @param conditionValue  The future computing the value for validation.
 * @param future          The actual value future.
 * @param validator       A validator for the condition.
 *
 * @return a new {@link ListenableFuture} eventually either containing
 * {@param future} or any exception thrown by {@param validator}.
 */
public static <A, B> ListenableFuture<A> fastFail(final ListenableFuture<B> conditionValue,
        final ListenableFuture<A> future, final Validator<B> validator) {
    return Futures.transform(conditionValue, new AsyncFunction<B, A>() {
        @Override
        public ListenableFuture<A> apply(B value) throws Exception {
            try {
                validator.validate(value);
                return future;

            } catch (Exception e) {
                future.cancel(false);
                throw e;
            }
        }
    });
}