List of usage examples for com.google.common.util.concurrent ListenableFuture get
V get() throws InterruptedException, ExecutionException;
From source file:net.oneandone.troilus.ListenableFutures.java
public static <T> T getUninterruptibly(ListenableFuture<T> future) { try {//from w ww .j a v a2 s .c o m return future.get(); } catch (ExecutionException | InterruptedException | RuntimeException e) { throw unwrapIfNecessary(e); } }
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 ww .j av a 2 s .co m * * @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; }
From source file:io.grpc.services.ChannelzProtoUtil.java
private static <T> T getFuture(ListenableFuture<T> future) { try {//from w w w . ja v a2 s . co m T ret = future.get(); if (ret == null) { throw Status.UNIMPLEMENTED.withDescription("The entity's stats can not be retrieved. " + "If this is an InProcessTransport this is expected.").asRuntimeException(); } return ret; } catch (InterruptedException e) { throw Status.INTERNAL.withCause(e).asRuntimeException(); } catch (ExecutionException e) { throw Status.INTERNAL.withCause(e).asRuntimeException(); } }
From source file:co.paralleluniverse.fibers.futures.AsyncListenableFuture.java
/** * Blocks the current strand (either fiber or thread) until the given future completes, and returns its result. * * @param future the future//from www .ja v a 2 s .co m * @return the future's result * @throws ExecutionException if the future's computation threw an exception * @throws InterruptedException if the current thread was interrupted while waiting */ public static <V> V get(ListenableFuture<V> future) throws ExecutionException, InterruptedException, SuspendExecution { if (Fiber.isCurrentFiber() && !future.isDone()) return new AsyncListenableFuture<>(future).run(); else return future.get(); }
From source file:com.helion3.prism.util.DataUtil.java
public static CompletableFuture<List<Result>> translateUuidsToNames(List<Result> results, List<UUID> uuidsPendingLookup) { CompletableFuture<List<Result>> future = new CompletableFuture<List<Result>>(); ListenableFuture<Collection<GameProfile>> profiles = Prism.getGame().getServer().getGameProfileManager() .getAllById(uuidsPendingLookup, true); profiles.addListener(() -> {/*from w w w. j a v a 2s . c o m*/ try { for (GameProfile profile : profiles.get()) { for (Result r : results) { Optional<Object> cause = r.data.get(DataQueries.Cause); if (cause.isPresent() && ((String) cause.get()).equals(profile.getUniqueId().toString())) { r.data.set(DataQueries.Cause, profile.getName()); } } } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } future.complete(results); }, MoreExecutors.sameThreadExecutor()); return future; }
From source file:org.hawkular.rx.cassandra.driver.RxUtil.java
/** * Converts from {@link ListenableFuture} to {@link rx.Observable}. * * @param future the {@link ListenableFuture} to register a listener on. * @param executor the {@link Executor} where the callback will be executed. The will be where the * {@link Observer#onNext(Object)} call from. * @return an {@link Observable} that emits the one value when the future completes. *//*www . ja v a2 s . co m*/ public static <T> Observable<T> from(final ListenableFuture<T> future, final Executor executor) { return Observable.create(new Observable.OnSubscribe<T>() { @Override public void call(final Subscriber<? super T> subscriber) { future.addListener(new Runnable() { @Override public void run() { try { T t = future.get(); subscriber.onNext(t); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }, executor); } }); }
From source file:org.springframework.data.cassandra.core.cql.session.DefaultBridgedReactiveSession.java
/** * Adapt {@link ListenableFuture} signals (completion, error) and propagate these to {@link MonoSink}. * * @param future the originating future. * @param sink the sink receiving signals. *//*from www . j a v a 2 s. c om*/ private static <T> void adaptFuture(ListenableFuture<T> future, MonoSink<T> sink) { future.addListener(() -> { if (future.isDone()) { try { sink.success(future.get()); } catch (ExecutionException cause) { sink.error(cause.getCause()); } catch (Exception cause) { sink.error(cause); } } }, Runnable::run); }
From source file:org.opendaylight.controller.cluster.datastore.ThreePhaseCommitCohortProxy.java
private static boolean successfulFuture(ListenableFuture<Void> future) { if (!future.isDone()) { return false; }//w w w.j a v a2s . c om try { future.get(); return true; } catch (Exception e) { return false; } }
From source file:com.android.tools.idea.fd.FlightRecorder.java
private static String getDeviceLogFileName(@NotNull AndroidDevice device) { // for avds, everything we need is already included in idea.log if (device.isVirtual()) { return "TARGET-AVD"; }/*from w w w.j a v a 2 s.c om*/ ListenableFuture<IDevice> launchedDevice = device.getLaunchedDevice(); if (!launchedDevice.isDone()) { return "OFFLINE"; } IDevice d; try { d = launchedDevice.get(); } catch (InterruptedException | ExecutionException e) { return "OFFLINE"; } return DevicePropertyUtil.getManufacturer(d, "unknown").replace(' ', '.') + '-' + DevicePropertyUtil.getModel(d, "unknown").replace(' ', '.'); }
From source file:com.sri.ai.util.concurrent.BranchAndMerge.java
private static <V, T> Result<T> executeConcurrent(List<? extends Callable<V>> tasks, Predicate<V> cancelOutstandingOnSuccess, Predicate<Throwable> cancelOutstandingOnFailure, Function<List<V>, T> transformResults) { boolean failureOccurred = false; T result = null;//from ww w . j ava 2s . c om try { List<Future<V>> invokedFutures = _sharedExecutorService.invokeAll(tasks); List<ListenableFuture<V>> lfutures = new ArrayList<ListenableFuture<V>>(); for (Future<V> future : invokedFutures) { lfutures.add((ListenableFuture<V>) future); } CancelOutstandingCallback<V> cancelOutstandingCallback = new CancelOutstandingCallback<V>( cancelOutstandingOnSuccess, cancelOutstandingOnFailure, lfutures); for (ListenableFuture<V> future : lfutures) { Futures.addCallback(future, cancelOutstandingCallback); } ListenableFuture<List<V>> resultsFuture = Futures.successfulAsList(lfutures); List<V> resultValues = resultsFuture.get(); if (cancelOutstandingCallback.failureOccurred()) { failureOccurred = true; // If I don't cancel outstanding on failure // then I'll attempt to create a result if (!cancelOutstandingOnFailure.apply(null)) { result = transformResults.apply(resultValues); } } else { result = transformResults.apply(resultValues); } } catch (Throwable t) { failureOccurred = true; } return new DefaultResult<T>(failureOccurred, result); }