List of usage examples for com.google.common.util.concurrent ListenableFuture get
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
From source file:org.opendaylight.netconf.test.tool.client.stress.AsyncExecutionStrategy.java
@Override public void invoke() { final AtomicInteger responseCounter = new AtomicInteger(0); final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList(); int batchI = 0; for (final Integer editBatch : getEditBatches()) { for (int i = 0; i < editBatch; i++) { final int msgId = i + (batchI * getParams().editBatchSize); final NetconfMessage msg = getPreparedMessages().get(msgId); LOG.debug("Sending message {}", msgId); if (LOG.isDebugEnabled()) { LOG.debug("Sending message {}", XmlUtil.toString(msg.getDocument())); }// www . j a v a 2 s .c o m final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture = getSessionListener() .sendRequest(msg, StressClient.EDIT_QNAME); futures.add(netconfMessageFuture); } batchI++; LOG.info("Batch {} with size {} sent. Committing", batchI, editBatch); if (getParams().candidateDatastore) { futures.add(getSessionListener().sendRequest(StressClient.COMMIT_MSG, StressClient.COMMIT_QNAME)); } } LOG.info("All batches sent. Waiting for responses"); // Wait for every future for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) { try { final RpcResult<NetconfMessage> netconfMessageRpcResult = future.get(getParams().msgTimeout, TimeUnit.SECONDS); if (netconfMessageRpcResult.isSuccessful()) { responseCounter.incrementAndGet(); LOG.debug("Received response {}", responseCounter.get()); } else { LOG.warn("Request failed {}", netconfMessageRpcResult); } } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException | TimeoutException e) { throw new RuntimeException("Request not finished", e); } } Preconditions.checkState( responseCounter.get() == getEditAmount() + (getParams().candidateDatastore ? getEditBatches().size() : 0), "Not all responses were received, only %s from %s", responseCounter.get(), getParams().editCount + getEditBatches().size()); }
From source file:com.twitter.heron.spi.statemgr.SchedulerStateManagerAdaptor.java
/** * Waits for ListenableFuture to terminate. Cancels on timeout *///from w w w .j ava2 s . c o m protected <V> V awaitResult(ListenableFuture<V> future, int time, TimeUnit unit) { try { return future.get(time, unit); } catch (InterruptedException | TimeoutException | ExecutionException e) { LOG.log(Level.SEVERE, "Exception processing future ", e); future.cancel(true); return null; } }
From source file:org.opendaylight.controller.netconf.test.tool.client.stress.AsyncExecutionStrategy.java
@Override public void invoke() { final AtomicInteger responseCounter = new AtomicInteger(0); final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList(); int batchI = 0; for (final Integer editBatch : editBatches) { for (int i = 0; i < editBatch; i++) { final int msgId = i + (batchI * params.editBatchSize); final NetconfMessage msg = preparedMessages.get(msgId); LOG.debug("Sending message {}", msgId); if (LOG.isDebugEnabled()) { LOG.debug("Sending message {}", XmlUtil.toString(msg.getDocument())); }/* w w w . j a v a 2 s . c om*/ final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture = sessionListener .sendRequest(msg, StressClient.EDIT_QNAME); futures.add(netconfMessageFuture); } batchI++; LOG.info("Batch {} with size {} sent. Committing", batchI, editBatch); futures.add(sessionListener.sendRequest(StressClient.COMMIT_MSG, StressClient.COMMIT_QNAME)); } LOG.info("All batches sent. Waiting for responses"); // Wait for every future for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) { try { final RpcResult<NetconfMessage> netconfMessageRpcResult = future.get(params.msgTimeout, TimeUnit.SECONDS); if (netconfMessageRpcResult.isSuccessful()) { responseCounter.incrementAndGet(); LOG.debug("Received response {}", responseCounter.get()); } else { LOG.warn("Request failed {}", netconfMessageRpcResult); } } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException | TimeoutException e) { throw new RuntimeException("Request not finished", e); } } Preconditions.checkState(responseCounter.get() == editAmount + editBatches.size(), "Not all responses were received, only %s from %s", responseCounter.get(), params.editCount + editBatches.size()); }
From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpAggregatedIngestionHandler.java
@Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); requestCount.inc();/*from ww w . j a v a 2 s. co m*/ final Timer.Context timerContext = handlerTimer.time(); String body = null; String submitterTenantId = request.headers().get(HttpMetricsIngestionServer.TENANT_ID_HEADER); int metricsCount = 0; int delayedMetricsCount = 0; try { // this is all JSON. body = request.content().toString(Constants.DEFAULT_CHARSET); MetricsCollection collection = new MetricsCollection(); AggregatedPayload payload = AggregatedPayload.create(body); long ingestTime = clock.now().getMillis(); if (payload.hasDelayedMetrics(ingestTime)) { Tracker.getInstance().trackDelayedAggregatedMetricsTenant(payload.getTenantId(), payload.getTimestamp(), payload.getDelayTime(ingestTime), payload.getAllMetricNames()); payload.markDelayMetricsReceived(ingestTime); delayedMetricsCount += payload.getAllMetricNames().size(); } else { metricsCount += payload.getAllMetricNames().size(); } List<ErrorResponse.ErrorData> validationErrors = payload.getValidationErrors(); if (validationErrors.isEmpty()) { // no validation errors, process bundle collection.add(PreaggregateConversions.buildMetricsCollection(payload)); ListenableFuture<List<Boolean>> futures = processor.apply(collection); List<Boolean> persisteds = futures.get(timeout.getValue(), timeout.getUnit()); for (Boolean persisted : persisteds) { if (!persisted) { log.error("Internal error persisting data for tenantId:" + payload.getTenantId()); DefaultHandler.sendErrorResponse(ctx, request, "Internal error persisting data", HttpResponseStatus.INTERNAL_SERVER_ERROR); return; } } recordPerTenantMetrics(submitterTenantId, metricsCount, delayedMetricsCount); DefaultHandler.sendResponse(ctx, request, null, HttpResponseStatus.OK); } else { // has validation errors for the single metric, return BAD_REQUEST DefaultHandler.sendErrorResponse(ctx, request, validationErrors, HttpResponseStatus.BAD_REQUEST); } } catch (JsonParseException ex) { log.debug(String.format("BAD JSON: %s", body)); DefaultHandler.sendErrorResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (InvalidDataException ex) { log.debug(String.format("Invalid request body: %s", body)); DefaultHandler.sendErrorResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (TimeoutException ex) { DefaultHandler.sendErrorResponse(ctx, request, "Timed out persisting metrics", HttpResponseStatus.ACCEPTED); } catch (Exception ex) { log.debug(String.format("JSON request payload: %s", body)); log.error("Error saving data", ex); DefaultHandler.sendErrorResponse(ctx, request, "Internal error saving data", HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { timerContext.stop(); requestCount.dec(); } }
From source file:org.jclouds.samples.googleappengine.GetAllResourcesController.java
private void blockUntilAllDoneOrCancelOnTimeout(Iterable<? extends ListenableFuture<?>> asyncResources) { try {/* w w w .j a v a 2 s. c o m*/ for (ListenableFuture<?> asyncResource : asyncResources) { if (remainingMillis.get() > 0) { try { asyncResource.get(remainingMillis.get(), TimeUnit.MILLISECONDS); } catch (Exception e) { logger.info("exception getting resource %s: %s", asyncResource, e.getMessage()); } } } } finally { if (remainingMillis.get() < 0) { for (ListenableFuture<?> asyncResource : asyncResources) { if (!asyncResource.isDone()) asyncResource.cancel(true); } } } }
From source file:org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.java
private void checkComplete() { final int size = futures.size(); if (size == 0) { return;//from ww w . j a va2 s . com } // Guards iteration against concurrent modification from callbacks synchronized (futures) { int offset = 0; for (ListenableFuture<Void> future : futures) { try { future.get(0, TimeUnit.NANOSECONDS); } catch (final TimeoutException e) { LOG.warn("Future #{}/{} not completed yet", offset, size); } catch (final ExecutionException e) { LOG.warn("Future #{}/{} failed", offset, size, e.getCause()); } catch (final InterruptedException e) { LOG.warn("Interrupted while examining future #{}/{}", offset, size, e); } ++offset; } } state = State.FAILED; runTimedOut(new TimeoutException("Collection did not finish in " + DEAD_TIMEOUT_SECONDS + " seconds")); }
From source file:com.google.caliper.runner.target.ProxyConnectionService.java
private void waitForAllVmsToExit(long timeout, TimeUnit unit) { if (vms.isEmpty()) { return;/*from w ww. ja v a2 s . c om*/ } List<ListenableFuture<?>> exitFutures = new ArrayList<>(); for (VmProxy vm : vms.values()) { exitFutures.add(vm.exitCode); } ListenableFuture<?> allExited = Futures.allAsList(exitFutures); try { allExited.get(timeout, unit); } catch (Exception ignore) { // oh well return; } // ensure the shutdown hooks are removed for (VmProxy vm : vms.values()) { try { vm.awaitExit(); } catch (InterruptedException e) { throw new AssertionError(e); } } }
From source file:co.cask.cdap.explore.client.ExploreFacade.java
private void handleExploreFuture(ListenableFuture future, String operation, String type, String name) throws ExploreException, SQLException { try {/*from w w w . j a v a2 s . c om*/ future.get(20, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.error("Caught exception", e); Thread.currentThread().interrupt(); } catch (ExecutionException e) { Throwable t = Throwables.getRootCause(e); if (t instanceof ExploreException) { LOG.error("{} explore did not finish successfully for {} instance {}.", operation, type, name); throw (ExploreException) t; } else if (t instanceof SQLException) { throw (SQLException) t; } else if (t instanceof HandleNotFoundException) { // Cannot happen unless explore server restarted, or someone calls close in between. LOG.error("Error running {} explore", operation, e); throw Throwables.propagate(e); } else if (t instanceof UnexpectedQueryStatusException) { UnexpectedQueryStatusException sE = (UnexpectedQueryStatusException) t; LOG.error("{} explore operation ended in an unexpected state - {}", operation, sE.getStatus().name(), e); throw Throwables.propagate(e); } } catch (TimeoutException e) { LOG.error("Error running {} explore - operation timed out", operation, e); throw Throwables.propagate(e); } }
From source file:c5db.log.OLogShim.java
@Override public void sync() throws IOException { // TODO how should this handle a case where some writes succeed and others fail? // TODO currently it throws an exception, but that can lead to the appearance that a successful write failed List<ListenableFuture<ReplicateSubmissionInfo>> appendFutureList = new ArrayList<>(); appendFutures.drainTo(appendFutureList); try {/*from w w w.jav a2s. co m*/ for (ListenableFuture<ReplicateSubmissionInfo> appendFuture : appendFutureList) { appendFuture.get(WAL_SYNC_TIMEOUT_SECONDS, TimeUnit.SECONDS).completedFuture .get(WAL_SYNC_TIMEOUT_SECONDS, TimeUnit.SECONDS); } } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new IOException("Error encountered while waiting within OLogShim#sync", e); } }
From source file:org.apache.qpid.server.SystemLauncher.java
public void shutdown(int exitStatusCode) { try {/*from w w w . ja va2 s . c om*/ if (_systemConfig != null) { ListenableFuture<Void> closeResult = _systemConfig.closeAsync(); closeResult.get(30000l, TimeUnit.MILLISECONDS); } } catch (TimeoutException | InterruptedException | ExecutionException e) { LOGGER.warn("Attempting to cleanly shutdown took too long, exiting immediately"); _listener.exceptionOnShutdown(e); } catch (RuntimeException e) { _listener.exceptionOnShutdown(e); throw e; } finally { cleanUp(exitStatusCode); } }