List of usage examples for com.google.common.util.concurrent ListenableFuture addListener
void addListener(Runnable listener, Executor executor);
From source file:io.prestosql.server.remotetask.ContinuousTaskStatusFetcher.java
private synchronized void scheduleNextRequest() { // stopped or done? TaskStatus taskStatus = getTaskStatus(); if (!running || taskStatus.getState().isDone()) { return;//from w w w. j a v a2 s. c o m } // outstanding request? if (future != null && !future.isDone()) { // this should never happen log.error("Can not reschedule update because an update is already running"); return; } // if throttled due to error, asynchronously wait for timeout and try again ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit(); if (!errorRateLimit.isDone()) { errorRateLimit.addListener(this::scheduleNextRequest, executor); return; } Request request = prepareGet().setUri(uriBuilderFrom(taskStatus.getSelf()).appendPath("status").build()) .setHeader(CONTENT_TYPE, JSON_UTF_8.toString()) .setHeader(PRESTO_CURRENT_STATE, taskStatus.getState().toString()) .setHeader(PRESTO_MAX_WAIT, refreshMaxWait.toString()).build(); errorTracker.startRequest(); future = httpClient.executeAsync(request, createFullJsonResponseHandler(taskStatusCodec)); currentRequestStartNanos.set(System.nanoTime()); Futures.addCallback(future, new SimpleHttpResponseHandler<>(this, request.getUri(), stats), executor); }
From source file:com.facebook.presto.server.remotetask.TaskInfoFetcher.java
private synchronized void sendNextRequest() { TaskStatus taskStatus = getTaskInfo().getTaskStatus(); if (!running) { return;//from www. jav a 2 s. c o m } // we already have the final task info if (isDone(getTaskInfo())) { stop(); return; } // if we have an outstanding request if (future != null && !future.isDone()) { return; } // if throttled due to error, asynchronously wait for timeout and try again ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit(); if (!errorRateLimit.isDone()) { errorRateLimit.addListener(this::sendNextRequest, executor); return; } HttpUriBuilder httpUriBuilder = uriBuilderFrom(taskStatus.getSelf()); URI uri = summarizeTaskInfo ? httpUriBuilder.addParameter("summarize").build() : httpUriBuilder.build(); Request request = prepareGet().setUri(uri).setHeader(CONTENT_TYPE, JSON_UTF_8.toString()).build(); errorTracker.startRequest(); future = httpClient.executeAsync(request, createFullJsonResponseHandler(taskInfoCodec)); currentRequestStartNanos.set(System.nanoTime()); Futures.addCallback(future, new SimpleHttpResponseHandler<>(this, request.getUri(), stats), executor); }
From source file:com.vangav.backend.thread_pool.ThreadPool.java
/** * executeInCassandraPool/*from ww w . j a va 2s.c om*/ * executes a listenable future in the blocking thread pool * @param listenableFuture: object to execute * @return result when ready (sleeps meanwhile) * @throws Exception */ public <T> void executeInCassandraPool(ListenableFuture<T> listenableFuture) throws Exception { WaitObject waitObject = new WaitObject(); listenableFuture.addListener(new NotifyRunnable(waitObject), this.cassandraPool); synchronized (waitObject) { if (waitObject.notified.get() == false) { waitObject.wait(); } } }
From source file:org.springframework.cassandra.core.session.DefaultBridgedReactiveSession.java
@Override public Mono<PreparedStatement> prepare(RegularStatement statement) { Assert.notNull(statement, "Statement must not be null"); return Mono.defer(() -> { try {// ww w. j ava 2s. c o m if (logger.isDebugEnabled()) { logger.debug("Preparing Statement [{}]", statement); } CompletableFuture<PreparedStatement> future = new CompletableFuture<>(); ListenableFuture<PreparedStatement> resultSetFuture = session.prepareAsync(statement); resultSetFuture.addListener(() -> { if (resultSetFuture.isDone()) { try { future.complete(resultSetFuture.get()); } catch (Exception e) { future.completeExceptionally(e); } } }, Runnable::run); return Mono.fromFuture(future); } catch (Exception e) { return Mono.error(e); } }).subscribeOn(scheduler); }
From source file:com.continuuity.loom.scheduler.SolverScheduler.java
@Override public void run() { try {//from w w w .j av a 2 s .c o m while (true) { final GroupElement gElement = solverQueues.take(id); if (gElement == null) { return; } final Element solveElement = gElement.getElement(); final ListenableFuture<String> future = executorService.submit(new SolverRunner(gElement)); future.addListener(new Runnable() { @Override public void run() { try { solverQueues.recordProgress(id, gElement.getQueueName(), solveElement.getId(), TrackingQueue.ConsumingStatus.FINISHED_SUCCESSFULLY, future.get()); } catch (Exception e) { LOG.error("Unable to record progress for cluster {}", solveElement.getId()); } } }, executorService); } } catch (Exception e) { LOG.error("Got exception:", e); } }
From source file:org.onosproject.store.flowext.impl.DefaultFlowRuleExtRouter.java
@Activate public void activate() { messageHandlingExecutor = Executors.newFixedThreadPool(MESSAGE_HANDLER_THREAD_POOL_SIZE, groupedThreads("onos/flow", "message-handlers")); clusterCommunicator.addSubscriber(APPLY_EXTEND_FLOWS, new ClusterMessageHandler() { @Override/*from w w w .ja v a 2 s . c o m*/ public void handle(ClusterMessage message) { // decode the extended flow entry and store them in memory. FlowRuleBatchRequest operation = SERIALIZER.decode(message.payload()); log.info("received batch request {}", operation); final ListenableFuture<FlowExtCompletedOperation> f = applyBatchInternal(operation); f.addListener(new Runnable() { @Override public void run() { FlowExtCompletedOperation result = Futures.getUnchecked(f); try { message.respond(SERIALIZER.encode(result)); } catch (IOException e) { log.error("Failed to respond back", e); } } }, futureListeners); } }, messageHandlingExecutor); replicaInfoManager.addListener(replicaInfoEventListener); log.info("Started"); }
From source file:com.continuuity.weave.discovery.ZKDiscoveryService.java
private void updateService(NodeChildren children, final String service) { final String sb = "/" + service; final Multimap<String, Discoverable> newServices = HashMultimap.create(services.get()); newServices.removeAll(service);//from w ww. j av a 2 s . c om // Fetch data of all children nodes in parallel. List<OperationFuture<NodeData>> dataFutures = Lists.newArrayListWithCapacity(children.getChildren().size()); for (String child : children.getChildren()) { String path = sb + "/" + child; dataFutures.add(zkClient.getData(path)); } // Update the service map when all fetching are done. final ListenableFuture<List<NodeData>> fetchFuture = Futures.successfulAsList(dataFutures); fetchFuture.addListener(new Runnable() { @Override public void run() { for (NodeData nodeData : Futures.getUnchecked(fetchFuture)) { // For successful fetch, decode the content. if (nodeData != null) { Discoverable discoverable = decode(nodeData.getData()); if (discoverable != null) { newServices.put(service, discoverable); } } } // Replace the local service register with changes. services.set(newServices); } }, Threads.SAME_THREAD_EXECUTOR); }
From source file:io.prestosql.plugin.thrift.ThriftPageSource.java
private CompletableFuture<PrestoThriftPageResult> sendDataRequestInternal() { long start = System.nanoTime(); ListenableFuture<PrestoThriftPageResult> rowsBatchFuture = client.getRows(splitId, columnNames, maxBytesPerResponse, new PrestoThriftNullableToken(nextToken)); rowsBatchFuture = catchingThriftException(rowsBatchFuture); rowsBatchFuture.addListener(() -> readTimeNanos.addAndGet(System.nanoTime() - start), directExecutor()); return toCompletableFuture(nonCancellationPropagating(rowsBatchFuture)); }
From source file:com.facebook.presto.memory.DefaultQueryContext.java
@Override public synchronized void setMemoryPool(MemoryPool newMemoryPool) { // This method first acquires the monitor of this instance. // After that in this method if we acquire the monitors of the // user/revocable memory contexts in the queryMemoryContext instance // (say, by calling queryMemoryContext.getUserMemory()) it's possible // to have a deadlock. Because, the driver threads running the operators // will allocate memory concurrently through the child memory context -> ... -> // root memory context -> this.updateUserMemory() calls, and will acquire // the monitors of the user/revocable memory contexts in the queryMemoryContext instance // first, and then the monitor of this, which may cause deadlocks. // That's why instead of calling methods on queryMemoryContext to get the // user/revocable memory reservations, we call the MemoryPool to get the same // information. requireNonNull(newMemoryPool, "newMemoryPool is null"); if (memoryPool == newMemoryPool) { // Don't unblock our tasks and thrash the pools, if this is a no-op return;// w ww . j a va 2 s. co m } ListenableFuture<?> future = memoryPool.moveQuery(queryId, newMemoryPool); memoryPool = newMemoryPool; future.addListener(() -> { // Unblock all the tasks, if they were waiting for memory, since we're in a new pool. taskContexts.values().forEach(TaskContext::moreMemoryAvailable); }, directExecutor()); }
From source file:org.jclouds.openstack.swift.blobstore.strategy.internal.ParallelMultipartUploadStrategy.java
protected void prepareUploadPart(final String container, final Blob blob, final String key, final Integer part, final Payload payload, final long offset, final long size, final SortedMap<Integer, String> etags, final BlockingQueue<Integer> activeParts, final Map<Integer, ListenableFuture<String>> futureParts, final AtomicInteger errors, final int maxRetries, final Map<Integer, Exception> errorMap, final Queue<Part> toRetry, final CountDownLatch latch, BlobToObject blob2Object) { if (errors.get() > maxRetries) { activeParts.remove(part); // remove part from the bounded-queue without blocking latch.countDown();/* w w w .j a v a 2 s.co m*/ return; } final CommonSwiftAsyncClient client = ablobstore.getContext().unwrap(SwiftApiMetadata.CONTEXT_TOKEN) .getAsyncApi(); Payload chunkedPart = slicer.slice(payload, offset, size); logger.debug(String.format("async uploading part %s of %s to container %s", part, key, container)); final long start = System.currentTimeMillis(); String blobPartName = blob.getMetadata().getName() + PART_SEPARATOR + String.valueOf(part); Blob blobPart = ablobstore.blobBuilder(blobPartName).payload(chunkedPart).contentDisposition(blobPartName) .build(); final ListenableFuture<String> futureETag = client.putObject(container, blob2Object.apply(blobPart)); futureETag.addListener(new Runnable() { @Override public void run() { try { etags.put(part, futureETag.get()); logger.debug(String.format("async uploaded part %s of %s to container %s in %sms", part, key, container, System.currentTimeMillis() - start)); } catch (CancellationException e) { errorMap.put(part, e); String message = String.format( "%s while uploading part %s - [%s,%s] to container %s with running since %dms", e.getMessage(), part, offset, size, container, System.currentTimeMillis() - start); logger.debug(message); } catch (Exception e) { errorMap.put(part, e); String message = String.format( "%s while uploading part %s - [%s,%s] to container %s running since %dms", e.getMessage(), part, offset, size, container, System.currentTimeMillis() - start); logger.error(message, e); if (errors.incrementAndGet() <= maxRetries) toRetry.add(new Part(part, offset, size)); } finally { activeParts.remove(part); // remove part from the bounded-queue without blocking futureParts.remove(part); latch.countDown(); } } }, ioExecutor); futureParts.put(part, futureETag); }