List of usage examples for com.google.common.util.concurrent ListenableFuture addListener
void addListener(Runnable listener, Executor executor);
From source file:com.facebook.buck.rules.modern.builders.RemoteExecutionStrategy.java
private ListenableFuture<Optional<BuildResult>> sendFailedEventOnException( ListenableFuture<Optional<BuildResult>> futureToBeWrapped, BuildTarget buildTarget, Digest actionDigest) {/*from ww w . jav a 2 s . co m*/ futureToBeWrapped.addListener(() -> { Optional<Throwable> exception = Optional.empty(); try { futureToBeWrapped.get(); } catch (InterruptedException e) { exception = Optional.of(e); } catch (ExecutionException e) { exception = Optional.of(e.getCause()); } if (exception.isPresent()) { RemoteExecutionActionEvent.sendTerminalEvent(eventBus, exception.get() instanceof InterruptedException ? State.ACTION_CANCELLED : State.ACTION_FAILED, buildTarget, Optional.of(actionDigest)); } }, MoreExecutors.directExecutor()); return futureToBeWrapped; }
From source file:io.datakernel.service.ServiceGraph.java
private ListenableFuture<LongestPath> combineDependenciesFutures(List<ListenableFuture<LongestPath>> futures, Executor executor) {/*www.j a va 2s . com*/ if (futures.size() == 0) { return Futures.immediateFuture(null); } if (futures.size() == 1) { return futures.get(0); } final SettableFuture<LongestPath> settableFuture = SettableFuture.create(); final AtomicInteger atomicInteger = new AtomicInteger(futures.size()); final AtomicReference<LongestPath> bestPath = new AtomicReference<>(); final AtomicReference<Throwable> exception = new AtomicReference<>(); for (final ListenableFuture<LongestPath> future : futures) { future.addListener(new Runnable() { @Override public void run() { try { LongestPath path = future.get(); if (bestPath.get() == null || (path != null && path.totalTime > bestPath.get().totalTime)) { bestPath.set(path); } } catch (InterruptedException | ExecutionException e) { if (exception.get() == null) { exception.set(getRootCause(e)); } } if (atomicInteger.decrementAndGet() == 0) { if (exception.get() != null) { settableFuture.setException(exception.get()); } else { settableFuture.set(bestPath.get()); } } } }, executor); } return settableFuture; }
From source file:com.notifier.desktop.Application.java
protected <T extends Service & Named> Future<State> stopService(final T service, final String category) { logger.info("Stopping [{}] {}", service.getName(), category == null ? "" : category); final Future<State> future = service.stop(); ListenableFuture<State> listenableFuture = Futures.makeListenable(future); listenableFuture.addListener(new Runnable() { @Override//w w w. j a va2 s.com public void run() { try { future.get(); } catch (InterruptedException e) { return; } catch (ExecutionException e) { logger.error( "Error stopping [" + service.getName() + "]" + (category == null ? "" : " " + category), e.getCause()); } } }, executorService); return future; }
From source file:com.notifier.desktop.Application.java
protected <T extends Service & Named> Future<State> startService(final T service, final String category) { logger.info("Starting [{}] {}", service.getName(), category == null ? "" : category); final Future<Service.State> future = service.start(); ListenableFuture<State> listenableFuture = Futures.makeListenable(future); listenableFuture.addListener(new Runnable() { @Override// ww w . j ava 2s. co m public void run() { try { future.get(); } catch (InterruptedException e) { return; } catch (ExecutionException e) { logger.error( "Error starting [" + service.getName() + "]" + (category == null ? "" : " " + category), e.getCause()); notifyStartupError(e.getCause()); } } }, executorService); return future; }
From source file:com.cloudera.hadoop.hdfs.nfs.rpc.ClientInputHandler.java
private void execute(final SessionSecurityHandler<? extends Verifier> securityHandler, AccessPrivilege accessPrivilege, final RPCRequest request, RPCBuffer requestBuffer) throws RPCException { if (LOGGER.isDebugEnabled()) { LOGGER.debug(mSessionID + " starting xid " + request.getXidAsHexString()); }/*from www .java 2s.c o m*/ mHandler.beforeProcess(request); REQUEST applicationRequest = mHandler.createRequest(); applicationRequest.read(requestBuffer); if (applicationRequest instanceof RequiresCredentials) { RequiresCredentials requiresCredentials = (RequiresCredentials) applicationRequest; // check to ensure it's auth creds is above requiresCredentials.setCredentials((AuthenticatedCredentials) request.getCredentials()); } final ListenableFuture<RESPONSE> future = mHandler.process(request, applicationRequest, accessPrivilege, mClient.getInetAddress(), mSessionID); future.addListener(new Runnable() { @Override public void run() { try { writeApplicationResponse(securityHandler, request, future.get()); } catch (Throwable t) { LOGGER.error("Unexpected error processing request", t); } } }, MoreExecutors.sameThreadExecutor()); }
From source file:io.datakernel.service.ServiceGraph.java
private ListenableFuture<?> actionInThread(final boolean start, final Collection<Object> rootNodes) { final SettableFuture<?> resultFuture = SettableFuture.create(); final ExecutorService executor = newSingleThreadExecutor(); executor.execute(new Runnable() { @Override// w w w . ja va2 s.c o m public void run() { Map<Object, ListenableFuture<LongestPath>> futures = new HashMap<>(); List<ListenableFuture<LongestPath>> rootFutures = new ArrayList<>(); for (Object rootNode : rootNodes) { rootFutures.add(processNode(rootNode, start, futures, executor)); } final ListenableFuture<LongestPath> rootFuture = combineDependenciesFutures(rootFutures, executor); rootFuture.addListener(new Runnable() { @Override public void run() { try { LongestPath longestPath = rootFuture.get(); StringBuilder sb = new StringBuilder(); printLongestPath(sb, longestPath); if (sb.length() != 0) sb.deleteCharAt(sb.length() - 1); logger.info("Longest path:\n" + sb); resultFuture.set(null); executor.shutdown(); } catch (InterruptedException | ExecutionException e) { resultFuture.setException(getRootCause(e)); executor.shutdown(); } } }, executor); } }); return resultFuture; }
From source file:io.prestosql.operator.OperatorContext.java
private static void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture, AtomicReference<SettableFuture<?>> targetFutureReference) { if (!memoryPoolFuture.isDone()) { SettableFuture<?> currentMemoryFuture = targetFutureReference.get(); while (currentMemoryFuture.isDone()) { SettableFuture<?> settableFuture = SettableFuture.create(); // We can't replace one that's not done, because the task may be blocked on that future if (targetFutureReference.compareAndSet(currentMemoryFuture, settableFuture)) { currentMemoryFuture = settableFuture; } else { currentMemoryFuture = targetFutureReference.get(); }/*w w w . j a v a 2 s .com*/ } SettableFuture<?> finalMemoryFuture = currentMemoryFuture; // Create a new future, so that this operator can un-block before the pool does, if it's moved to a new pool memoryPoolFuture.addListener(() -> finalMemoryFuture.set(null), directExecutor()); } }
From source file:org.apache.cassandra.service.ActiveRepairService.java
/** * Submit anti-compaction jobs to CompactionManager. * When all jobs are done, parent repair session is removed whether those are suceeded or not. * * @param parentRepairSession parent repair session ID * @return Future result of all anti-compaction jobs. *//* w w w. j a v a 2 s . c o m*/ @SuppressWarnings("resource") public ListenableFuture<List<Object>> doAntiCompaction(final UUID parentRepairSession, Collection<Range<Token>> successfulRanges) { assert parentRepairSession != null; ParentRepairSession prs = getParentRepairSession(parentRepairSession); //A repair will be marked as not global if it is a subrange repair to avoid many small anti-compactions //in addition to other scenarios such as repairs not involving all DCs or hosts if (!prs.isGlobal) { logger.info("Not a global repair, will not do anticompaction"); removeParentRepairSession(parentRepairSession); return Futures.immediateFuture(Collections.emptyList()); } assert prs.ranges.containsAll(successfulRanges) : "Trying to perform anticompaction on unknown ranges"; List<ListenableFuture<?>> futures = new ArrayList<>(); // if we don't have successful repair ranges, then just skip anticompaction if (!successfulRanges.isEmpty()) { for (Map.Entry<UUID, ColumnFamilyStore> columnFamilyStoreEntry : prs.columnFamilyStores.entrySet()) { Refs<SSTableReader> sstables = prs.getAndReferenceSSTables(columnFamilyStoreEntry.getKey()); ColumnFamilyStore cfs = columnFamilyStoreEntry.getValue(); futures.add(CompactionManager.instance.submitAntiCompaction(cfs, successfulRanges, sstables, prs.repairedAt)); } } ListenableFuture<List<Object>> allAntiCompactionResults = Futures.successfulAsList(futures); allAntiCompactionResults.addListener(new Runnable() { @Override public void run() { removeParentRepairSession(parentRepairSession); } }, MoreExecutors.sameThreadExecutor()); return allAntiCompactionResults; }
From source file:com.google.devtools.build.lib.remote.ByteStreamUploader.java
@VisibleForTesting ListenableFuture<Void> uploadBlobAsync(Chunker chunker) throws IOException { Digest digest = checkNotNull(chunker.digest()); synchronized (lock) { checkState(!isShutdown, "Must not call uploadBlobs after shutdown."); ListenableFuture<Void> uploadResult = uploadsInProgress.get(digest); if (uploadResult == null) { uploadResult = SettableFuture.create(); uploadResult.addListener(() -> { synchronized (lock) { uploadsInProgress.remove(digest); }/* w w w .j a va 2 s. com*/ }, MoreExecutors.directExecutor()); startAsyncUploadWithRetry(chunker, retrier.newBackoff(), (SettableFuture<Void>) uploadResult); uploadsInProgress.put(digest, uploadResult); } return uploadResult; } }
From source file:io.datakernel.service.ServiceGraph.java
private ListenableFuture<LongestPath> processNode(final Object node, final boolean start, Map<Object, ListenableFuture<LongestPath>> futures, final Executor executor) { List<ListenableFuture<LongestPath>> dependencyFutures = new ArrayList<>(); for (Object dependencyNode : (start ? forwards : backwards).get(node)) { ListenableFuture<LongestPath> dependencyFuture = processNode(dependencyNode, start, futures, executor); dependencyFutures.add(dependencyFuture); }// w ww. java 2 s. com if (futures.containsKey(node)) { return futures.get(node); } final SettableFuture<LongestPath> future = SettableFuture.create(); futures.put(node, future); final ListenableFuture<LongestPath> dependenciesFuture = combineDependenciesFutures(dependencyFutures, executor); dependenciesFuture.addListener(new Runnable() { @Override public void run() { try { final LongestPath longestPath = dependenciesFuture.get(); Service service = services.get(node); if (service == null) { logger.debug("...skipping no-service node: " + nodeToString(node)); future.set(longestPath); return; } if (!start && !runningNodes.contains(node)) { logger.debug("...skipping not running node: " + nodeToString(node)); future.set(longestPath); return; } final Stopwatch sw = Stopwatch.createStarted(); final ListenableFuture<?> serviceFuture = (start ? service.start() : service.stop()); logger.info((start ? "Starting" : "Stopping") + " node: " + nodeToString(node)); serviceFuture.addListener(new Runnable() { @Override public void run() { try { serviceFuture.get(); if (start) { runningNodes.add(node); } else { runningNodes.remove(node); } long elapsed = sw.elapsed(MILLISECONDS); logger.info((start ? "Started" : "Stopped") + " " + nodeToString(node) + (elapsed >= 1L ? (" in " + sw) : "")); future.set( new LongestPath(elapsed + (longestPath != null ? longestPath.totalTime : 0), elapsed, node, longestPath)); } catch (InterruptedException | ExecutionException e) { logger.error("error: " + nodeToString(node), e); future.setException(getRootCause(e)); } } }, executor); } catch (InterruptedException | ExecutionException e) { future.setException(getRootCause(e)); } } }, executor); return future; }