List of usage examples for com.google.common.base Stopwatch elapsed
@CheckReturnValue public long elapsed(TimeUnit desiredUnit)
From source file:ddf.catalog.resource.download.ReliableResourceDownloadManager.java
/** * @param resourceRequest/*from ww w . jav a 2s.co m*/ * the original @ResourceRequest to retrieve the resource * @param metacard * the @Metacard associated with the resource being downloaded * @param retriever * the @ResourceRetriever to be used to get the resource * @return the modified @ResourceResponse with the @ReliableResourceInputStream that the client * should read from * @throws DownloadException */ public ResourceResponse download(ResourceRequest resourceRequest, Metacard metacard, ResourceRetriever retriever) throws DownloadException { if (metacard == null) { throw new DownloadException("Cannot download resource if metacard is null"); } else if (StringUtils.isBlank(metacard.getId())) { throw new DownloadException("Metacard must have unique id."); } else if (retriever == null) { throw new DownloadException("Cannot download resource if retriever is null"); } else if (resourceRequest == null) { throw new DownloadException("Cannot download resource if request is null"); } try { resourceResponse = retriever.retrieveResource(); } catch (ResourceNotFoundException | ResourceNotSupportedException | IOException e) { throw new DownloadException("Cannot download resource", e); } resourceResponse.getProperties().put(Metacard.ID, metacard.getId()); // Sources do not create ResourceResponses with the original ResourceRequest, hence // it is added here because it will be needed for caching resourceResponse = new ResourceResponseImpl(resourceRequest, resourceResponse.getProperties(), resourceResponse.getResource()); // TODO - this should be before retrieveResource() but eventPublisher requires a // resourceResponse and that resource response must have a resource request in it (to get // USER property) eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.STARTED, metacard, null, 0L, downloadIdentifier); AtomicBoolean downloadStarted = new AtomicBoolean(Boolean.FALSE); ReliableResourceDownloader downloader = new ReliableResourceDownloader(downloaderConfig, downloadStarted, downloadIdentifier, resourceResponse, retriever); resourceResponse = downloader.setupDownload(metacard, downloadStatusInfo); // Start download in separate thread so can return ResourceResponse with // ReliableResourceInputStream available for client to start reading from executor.submit(downloader); // Wait for download to get started before returning control to client Stopwatch stopwatch = Stopwatch.createStarted(); while (!downloadStarted.get()) { try { Thread.sleep(10); } catch (InterruptedException e) { } long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (elapsedTime > ONE_SECOND_IN_MS) { LOGGER.debug("downloadStarted still FALSE - elapsedTime = {}", elapsedTime); break; } } LOGGER.debug("elapsedTime = {}", stopwatch.elapsed(TimeUnit.MILLISECONDS)); stopwatch.stop(); return resourceResponse; }
From source file:org.glowroot.ui.HttpServer.java
void close() throws Exception { logger.debug("close(): stopping http server"); Future<?> workerShutdownFuture = workerGroup.shutdownGracefully(1, 5, SECONDS); Future<?> bossShutdownFuture = bossGroup.shutdownGracefully(1, 5, SECONDS); Stopwatch stopwatch = Stopwatch.createStarted(); workerShutdownFuture.get(10, SECONDS); long remainingMillis = Math.max(0, 10000 - stopwatch.elapsed(MILLISECONDS)); bossShutdownFuture.get(remainingMillis, MILLISECONDS); logger.debug("close(): http server stopped"); }
From source file:ezbake.groups.service.caching.RedisCacheLayer.java
private void logStopwatch(Stopwatch timer, String message, Object... args) { if (shouldLogTimers) { message = String.format(message, args); logger.info("TIMER: {} ----------> {}ms", message, timer.elapsed(TimeUnit.MILLISECONDS)); }/*from w w w . j av a2s.c o m*/ }
From source file:org.glowroot.agent.it.harness.impl.GrpcServerWrapper.java
void close() throws InterruptedException { Stopwatch stopwatch = Stopwatch.createStarted(); while (stopwatch.elapsed(SECONDS) < 10 && !downstreamService.closedByAgent) { MILLISECONDS.sleep(10);/*from w ww. j ava 2s. c o m*/ } checkState(downstreamService.closedByAgent); // TODO shutdownNow() has been needed to interrupt grpc threads since grpc-java 1.7.0 server.shutdownNow(); if (!server.awaitTermination(10, SECONDS)) { throw new IllegalStateException("Could not terminate channel"); } // not sure why, but server needs a little extra time to shut down properly // without this sleep, this warning is logged (but tests still pass): // io.grpc.netty.NettyServerHandler - Connection Error: RejectedExecutionException MILLISECONDS.sleep(100); executor.shutdown(); if (!executor.awaitTermination(10, SECONDS)) { throw new IllegalStateException("Could not terminate executor"); } if (!bossEventLoopGroup.shutdownGracefully(0, 0, SECONDS).await(10, SECONDS)) { throw new IllegalStateException("Could not terminate event loop group"); } if (!workerEventLoopGroup.shutdownGracefully(0, 0, SECONDS).await(10, SECONDS)) { throw new IllegalStateException("Could not terminate event loop group"); } }
From source file:ch.ge.ve.protopoc.service.protocol.DefaultVotingClient.java
@Override public String confirmVote(String confirmationCredentials) throws VoteConfirmationException { Preconditions.checkState(publicParameters != null, "The public parameters need to have been retrieved first"); Preconditions.checkState(electionSet != null, "The electionSet needs to have been retrieved first"); Preconditions.checkState(pointMatrix != null, "The point matrix needs to have been computed first"); Stopwatch stopwatch = Stopwatch.createStarted(); Confirmation confirmation = voteConfirmationClientAlgorithms.genConfirmation(confirmationCredentials, pointMatrix, voterSelectionCounts); stopwatch.stop();/*from w w w. ja v a 2 s . c o m*/ stats.confirmationEncodingTime = stopwatch.elapsed(TimeUnit.MILLISECONDS); List<FinalizationCodePart> finalizationCodeParts; try { finalizationCodeParts = bulletinBoardService.publishConfirmation(voterIndex, confirmation); } catch (IncorrectConfirmationRuntimeException e) { throw new VoteConfirmationException(e); } stopwatch.reset().start(); String finalizationCode = voteConfirmationClientAlgorithms.getFinalizationCode(finalizationCodeParts); stopwatch.stop(); stats.finalizationCodeComputationTime = stopwatch.elapsed(TimeUnit.MILLISECONDS); return finalizationCode; }
From source file:org.apache.jackrabbit.oak.run.DataStoreCheckCommand.java
private static void retrieveBlobReferences(GarbageCollectableBlobStore blobStore, BlobReferenceRetriever marker, File marked) throws IOException { final BufferedWriter writer = Files.newWriter(marked, Charsets.UTF_8); final AtomicInteger count = new AtomicInteger(); boolean threw = true; try {/*from w w w . ja v a2s . c o m*/ final Joiner delimJoiner = Joiner.on(DELIM).skipNulls(); final GarbageCollectableBlobStore finalBlobStore = blobStore; System.out.println("Starting dump of blob references"); Stopwatch watch = createStarted(); marker.collectReferences(new ReferenceCollector() { @Override public void addReference(String blobId, String nodeId) { try { Iterator<String> idIter = finalBlobStore.resolveChunks(blobId); while (idIter.hasNext()) { String id = delimJoiner.join(idIter.next(), nodeId); count.getAndIncrement(); writeAsLine(writer, id, true); } } catch (Exception e) { throw new RuntimeException("Error in retrieving references", e); } } }); writer.flush(); sort(marked, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.split(DELIM)[0].compareTo(s2.split(DELIM)[0]); } }); System.out.println(count.get() + " blob references found"); System.out.println("Finished in " + watch.elapsed(TimeUnit.SECONDS) + " seconds"); threw = false; } finally { close(writer, threw); } }
From source file:org.glowroot.agent.it.harness.impl.GrpcServerWrapper.java
AgentConfig getAgentConfig() throws InterruptedException { Stopwatch stopwatch = Stopwatch.createStarted(); while (agentConfig == null && stopwatch.elapsed(SECONDS) < 10) { MILLISECONDS.sleep(10);/*from w ww. jav a 2 s . com*/ } if (agentConfig == null) { throw new IllegalStateException("Timed out waiting to receive agent config"); } return agentConfig; }
From source file:org.apache.drill.exec.store.parquet.ParquetPushDownFilter.java
protected void doOnMatch(RelOptRuleCall call, FilterPrel filter, ProjectPrel project, ScanPrel scan) { ParquetGroupScan groupScan = (ParquetGroupScan) scan.getGroupScan(); if (groupScan.getFilter() != null && !groupScan.getFilter().equals(ValueExpressions.BooleanExpression.TRUE)) { return;// ww w . j a v a 2 s.co m } RexNode condition = null; if (project == null) { condition = filter.getCondition(); } else { // get the filter as if it were below the projection. condition = RelOptUtil.pushFilterPastProject(filter.getCondition(), project); } if (condition == null || condition.equals(ValueExpressions.BooleanExpression.TRUE)) { return; } LogicalExpression conditionExp = DrillOptiq .toDrill(new DrillParseContext(PrelUtil.getPlannerSettings(call.getPlanner())), scan, condition); Stopwatch timer = Stopwatch.createStarted(); final GroupScan newGroupScan = groupScan.applyFilter(conditionExp, optimizerContext, optimizerContext.getFunctionRegistry(), optimizerContext.getPlannerSettings().getOptions()); logger.info("Took {} ms to apply filter on parquet row groups. ", timer.elapsed(TimeUnit.MILLISECONDS)); if (newGroupScan == null) { return; } final ScanPrel newScanRel = ScanPrel.create(scan, scan.getTraitSet(), newGroupScan, scan.getRowType()); RelNode inputRel = newScanRel; if (project != null) { inputRel = project.copy(project.getTraitSet(), ImmutableList.of(inputRel)); } final RelNode newFilter = filter.copy(filter.getTraitSet(), ImmutableList.<RelNode>of(inputRel)); call.transformTo(newFilter); }
From source file:org.glowroot.agent.it.harness.Threads.java
public static void preShutdownCheck(Collection<Thread> preExistingThreads) throws InterruptedException { // give the test 5 seconds to shutdown any threads they may have created, e.g. give tomcat // time to shutdown when testing tomcat plugin Stopwatch stopwatch = Stopwatch.createStarted(); List<Thread> nonPreExistingThreads; List<Thread> rogueThreads; do {/* ww w . ja v a 2s.c om*/ nonPreExistingThreads = getNonPreExistingThreads(preExistingThreads); rogueThreads = Lists.newArrayList(); for (Thread thread : nonPreExistingThreads) { if (isRogueThread(thread)) { rogueThreads.add(thread); } } // check total number of threads to make sure Glowroot is not creating too many // // currently, the eight threads are: // // Glowroot-Background-0 // Glowroot-Background-1 // H2 Log Writer GLOWROOT // H2 File Lock Watchdog <lock db file> // Glowroot-GRPC-Worker-ELG-0 // Glowroot-GRPC-Executor-0 // Generate Seed // threadDeathWatcher-2-1 // grpc-shared-destroyer-0 if (rogueThreads.isEmpty() && nonPreExistingThreads.size() <= 8) { // success return; } // wait a few milliseconds before trying again MILLISECONDS.sleep(10); } while (stopwatch.elapsed(SECONDS) < 10); // failure if (!rogueThreads.isEmpty()) { throw new RogueThreadsException(rogueThreads); } else { throw new TooManyThreadsException(nonPreExistingThreads); } }
From source file:com.vmware.photon.controller.common.metrics.RpcMetricInterceptor.java
@Override public Object invoke(MethodInvocation invocation) throws Throwable { Stopwatch stopwatch = Stopwatch.createStarted(); String methodName = invocation.getMethod().getName(); try {/*ww w.j a va2 s. com*/ logger.info("Starting call to {}", methodName); return invocation.proceed(); } catch (Throwable t) { exceptions.mark(); logger.info("Caught exception during {}: {}", methodName, t); throw t; } finally { duration.update(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); logger.info("Finished call to {}", methodName); } }