Example usage for com.google.common.base Stopwatch elapsed

List of usage examples for com.google.common.base Stopwatch elapsed

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch elapsed.

Prototype

@CheckReturnValue
public long elapsed(TimeUnit desiredUnit) 

Source Link

Document

Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Usage

From source file:org.fenixedu.bennu.core.api.SystemResource.java

@GET
@Path("healthcheck")
@Produces(MediaType.APPLICATION_JSON)//from ww  w  .j  av a2s.  c o m
public JsonArray healthChecks() {
    accessControl(Group.managers());
    JsonArray json = new JsonArray();

    for (Healthcheck check : healthchecks) {
        JsonObject obj = new JsonObject();
        obj.addProperty("name", check.getName());
        Stopwatch stop = Stopwatch.createStarted();
        Result result = check.execute();
        stop.stop();
        obj.add("result", result.toJson());
        obj.addProperty("time", stop.elapsed(TimeUnit.MILLISECONDS));
        json.add(obj);
    }

    return json;
}

From source file:com.dssmp.agent.tailing.FileTailer.java

/**
 * @param timeout Use a value {@code <= 0} to wait indefinitely.
 * @param unit/*w  ww  .  j a  va 2s. c  om*/
 * @return {@code true} if idle state was reached before the timeout
 * expired, or {@code false} if idle state was not successfully
 * reached.
 */
public boolean waitForIdle(long timeout, TimeUnit unit) {
    Stopwatch timer = Stopwatch.createStarted();
    while (!isIdle()) {
        long remaining = timeout > 0 ? (unit.toMillis(timeout) - timer.elapsed(TimeUnit.MILLISECONDS))
                : Long.MAX_VALUE;
        if (remaining <= 0)
            return false;
        long sleepTime = Math.min(MAX_SPIN_WAIT_TIME_MILLIS, remaining);
        LOGGER.trace("{}: Waiting IDLE. Sleeping {}ms. {}", serviceName(), sleepTime, toString());
        publisher.flush();
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            // No need to make this method interruptible. Just return false signifying timeout.
            Thread.currentThread().interrupt();
            LOGGER.trace("{}: Thread interrupted while waiting for tailer to go idle.", serviceName(), e);
            return false;
        }
    }
    return true;
}

From source file:fr.ens.transcriptome.aozan.collectors.AbstractFastqProcessThread.java

@Override
public void run() {

    // Timer/*from  w  w  w  .ja v a 2s .c o  m*/
    final Stopwatch timer = Stopwatch.createStarted();

    notifyStartLogger();

    try {
        // Launch process treatment related to each collector
        process();

        setSuccess(true);

    } catch (final AozanException e) {
        setException(e);
    } finally {

        final String duration = toTimeHumanReadable(timer.elapsed(TimeUnit.MILLISECONDS));
        timer.stop();

        notifyEndLogger(duration);
    }

}

From source file:com.facebook.buck.distributed.DistBuildClientExecutor.java

public int executeAndPrintFailuresToEventBus(final WeightedListeningExecutorService executorService,
        ProjectFilesystem projectFilesystem, FileHashCache fileHashCache, BuckEventBus eventBus)
        throws IOException, InterruptedException {

    BuildJob job = distBuildService.createBuild();
    final BuildId id = job.getBuildId();
    LOG.info("Created job. Build id = " + id.getId());
    logDebugInfo(job);/*from ww w  . ja va 2 s.c om*/

    List<ListenableFuture<Void>> asyncJobs = new LinkedList<>();
    LOG.info("Uploading local changes.");
    asyncJobs.add(distBuildService.uploadMissingFiles(buildJobState.fileHashes, executorService));

    LOG.info("Uploading target graph.");
    asyncJobs.add(distBuildService.uploadTargetGraph(buildJobState, id, executorService));

    LOG.info("Uploading buck dot-files.");
    asyncJobs.add(distBuildService.uploadBuckDotFiles(id, projectFilesystem, fileHashCache, executorService));

    try {
        Futures.allAsList(asyncJobs).get();
    } catch (ExecutionException e) {
        LOG.error("Upload failed.");
        throw new RuntimeException(e);
    }

    distBuildService.setBuckVersion(id, buckVersion);
    LOG.info("Set Buck Version. Build status: " + job.getStatus().toString());

    job = distBuildService.startBuild(id);
    LOG.info("Started job. Build status: " + job.getStatus().toString());
    logDebugInfo(job);

    Stopwatch stopwatch = Stopwatch.createStarted();
    // Keep polling until the build is complete or failed.
    do {
        job = distBuildService.getCurrentBuildJobState(id);
        LOG.info("Got build status: " + job.getStatus().toString());

        DistBuildStatus distBuildStatus = prepareStatusFromJob(job)
                .setETAMillis(MAX_BUILD_DURATION_MILLIS - stopwatch.elapsed(TimeUnit.MILLISECONDS)).build();
        eventBus.post(new DistBuildStatusEvent(distBuildStatus));

        try {
            // TODO(shivanker): Get rid of sleeps in methods which we want to unit test
            Thread.sleep(millisBetweenStatusPoll);
        } catch (InterruptedException e) {
            LOG.error(e, "BuildStatus polling sleep call has been interrupted unexpectedly.");
        }
    } while (!(job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY)
            || job.getStatus().equals(BuildStatus.FAILED)));

    LOG.info("Build was " + (job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) ? "" : "not ")
            + "successful!");
    logDebugInfo(job);

    DistBuildStatus distBuildStatus = prepareStatusFromJob(job).setETAMillis(0).build();
    eventBus.post(new DistBuildStatusEvent(distBuildStatus));

    return job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) ? 0 : 1;
}

From source file:org.glowroot.agent.util.LazyPlatformMBeanServer.java

private void waitForContainerToCreatePlatformMBeanServer() throws Exception {
    synchronized (platformMBeanServerAvailability) {
        if (platformMBeanServerAvailable) {
            return;
        }/*w ww .java 2 s  .  c  o  m*/
        Stopwatch stopwatch = Stopwatch.createStarted();
        // looping to guard against "spurious wakeup" from Object.wait()
        while (!platformMBeanServerAvailable) {
            long remaining = SECONDS.toMillis(60) - stopwatch.elapsed(MILLISECONDS);
            if (remaining < 1000) {
                // less that one second remaining
                break;
            }
            platformMBeanServerAvailability.wait(remaining);
        }
        if (!platformMBeanServerAvailable) {
            logger.error("platform mbean server was never created by container");
        }
    }
}

From source file:appeng.services.export.ExportProcess.java

/**
 * Will check and export if various config settings will lead to exporting the CSV file.
 *//*w  w w .jav  a2s  .co m*/
@Override
public void run() {
    // no priority to this thread
    Thread.yield();

    // logic when to cancel the export process
    if (this.config.isForceRefreshEnabled()) {
        AELog.info(FORCE_REFRESH_MESSAGE);
    } else {
        if (this.config.isCacheEnabled()) {
            AELog.info(CACHE_ENABLED_MESSAGE);

            final Loader loader = Loader.instance();
            final List<ModContainer> mods = loader.getActiveModList();

            if (this.modChecker.isEqual(mods) == CheckType.EQUAL) {
                AELog.info(EQUAL_CONTENT_MESSAGE);

                return;
            } else {
                AELog.info(UNEQUAL_CONTENT_MESSAGE);
            }
        } else {
            AELog.info(CACHE_DISABLED_MESSAGE);
        }
    }

    AELog.info(EXPORT_START_MESSAGE);
    final Stopwatch watch = Stopwatch.createStarted();

    final FMLControlledNamespacedRegistry<Item> itemRegistry = GameData.getItemRegistry();

    final ExportMode mode = this.config.isAdditionalInformationEnabled() ? ExportMode.VERBOSE
            : ExportMode.MINIMAL;
    final Exporter exporter = new MinecraftItemCSVExporter(this.exportDirectory, itemRegistry, mode);

    exporter.export();

    AELog.info(EXPORT_END_MESSAGE, watch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:nl.knaw.huygens.timbuctoo.tools.conversion.DomainEntityCollectionConverter.java

public void convert() {
    String simpleName = type.getSimpleName();
    LOG.info("Start converting for {}", simpleName);
    List<DomainEntityConverter<T>> converters = Lists.newArrayList();
    try {//from  w  w w .  j  a v  a 2  s .  com
        //first create the jobs to prevent a mongo cursor timeout exception.      
        for (StorageIterator<T> iterator = mongoStorage.getDomainEntities(type); iterator.hasNext();) {
            T entity = iterator.next();
            String oldId = entity.getId();
            converters.add(entityConverterFactory.create(type, oldId));

        }
        Stopwatch stopwatch = Stopwatch.createStarted();
        int number = 0;
        for (DomainEntityConverter<T> converter : converters) {
            String oldId = converter.getOldId();
            try {
                converter.convert();

                if (number % 1000 == 0) {
                    commit();
                    LOG.info("Time per conversion: {} ms, number of conversions {}",
                            (double) stopwatch.elapsed(TimeUnit.MILLISECONDS) / number, number);
                }

                number++;
            } catch (IllegalArgumentException | IllegalAccessException e) {
                LOG.error("Could not convert {} with id \"{}\"", simpleName, oldId);
            }
        }
    } catch (StorageException e) {
        LOG.error("Could not retrieve DomainEntities of type \"{}\"", simpleName);
    } finally {
        LOG.info("End converting for {}.", simpleName);
        commit();
    }
}

From source file:org.glowroot.central.RollupService.java

@Override
public void run() {
    Session.setInRollupThread(true);//from w  ww .  j ava 2 s  . c  o m
    int counter = 0;
    int numWorkerThreads = INITIAL_WORKER_THREADS;
    ListeningExecutorService workerExecutor = newWorkerExecutor(numWorkerThreads);
    while (!closed) {
        try {
            MILLISECONDS.sleep(millisUntilNextRollup(clock.currentTimeMillis()));
            // perform larger sweep approx every 100 minutes
            long lastXMillis = counter++ % 100 == 0 ? DAYS.toMillis(7) : MINUTES.toMillis(30);
            Stopwatch stopwatch = Stopwatch.createStarted();
            List<AgentRollup> agentRollups = activeAgentDao.readRecentlyActiveAgentRollups(lastXMillis);
            runInternal(agentRollups, workerExecutor);
            long elapsedInSeconds = stopwatch.elapsed(SECONDS);
            int oldNumWorkerThreads = numWorkerThreads;
            if (elapsedInSeconds > 300) {
                if (numWorkerThreads < MAX_WORKER_THREADS) {
                    numWorkerThreads++;
                } else {
                    logger.warn(
                            "rolling up data across {} agent rollup took {} seconds (using" + " {} threads)",
                            count(agentRollups), elapsedInSeconds, numWorkerThreads);
                }
            } else if (elapsedInSeconds < 60 && numWorkerThreads > MIN_WORKER_THREADS) {
                numWorkerThreads--;
            }
            if (numWorkerThreads != oldNumWorkerThreads) {
                ExecutorService oldWorkerExecutor = workerExecutor;
                workerExecutor = newWorkerExecutor(numWorkerThreads);
                oldWorkerExecutor.shutdown();
                if (!oldWorkerExecutor.awaitTermination(10, SECONDS)) {
                    logger.error("timed out waiting for old worker rollup thread to terminate");
                }
            }
        } catch (InterruptedException e) {
            // probably shutdown requested (see close method below)
            logger.debug(e.getMessage(), e);
            continue;
        } catch (Throwable t) {
            // this probably should never happen since runInternal catches and logs exceptions
            logger.error(t.getMessage(), t);
        }
    }
    // shutdownNow() is needed here to send interrupt to worker rollup thread
    workerExecutor.shutdownNow();
    try {
        if (!workerExecutor.awaitTermination(10, SECONDS)) {
            throw new IllegalStateException("Timed out waiting for worker rollup thread to terminate");
        }
    } catch (InterruptedException e) {
        // this is unexpected (but not harmful since already closing)
        logger.error(e.getMessage(), e);
    }
}

From source file:com.palantir.atlasdb.sweep.BackgroundSweeper.java

private void saveSweepResults(Transaction t, SweepProgressRowResult progress, SweepResults results) {
    long cellsDeleted = getCellsDeleted(progress, results);
    long cellsExamined = getCellsExamined(progress, results);
    if (results.getNextStartRow().isPresent()) {
        SweepProgressTable progressTable = tableFactory.getSweepProgressTable(t);
        SweepProgressRow row = SweepProgressRow.of(0);
        progressTable.putFullTableName(row, progress.getFullTableName());
        progressTable.putStartRow(row, results.getNextStartRow().get());
        progressTable.putCellsDeleted(row, cellsDeleted);
        progressTable.putCellsExamined(row, cellsExamined);
    } else {/*from   ww  w  . j a va  2 s  .  c om*/
        SweepPriorityTable priorityTable = tableFactory.getSweepPriorityTable(t);
        SweepPriorityRow row = SweepPriorityRow.of(progress.getFullTableName());
        priorityTable.putCellsDeleted(row, cellsDeleted);
        priorityTable.putCellsExamined(row, cellsExamined);
        priorityTable.putLastSweepTime(row, System.currentTimeMillis());

        // Estimate that half of the new writes that occurred while sweeping got swept.
        Long currentWriteCount = priorityTable.getWriteCounts(ImmutableList.of(row)).get(row);
        long oldWriteCount = getOldWriteCount(row);
        if (currentWriteCount != null && currentWriteCount > oldWriteCount) {
            priorityTable.putWriteCount(row, currentWriteCount - oldWriteCount / 2);
        }

        log.info("Finished sweeping {}, examined {} unique cells, deleted {} cells.",
                progress.getFullTableName(), cellsExamined, cellsDeleted);

        if (cellsDeleted > 0) {
            Stopwatch watch = Stopwatch.createStarted();
            kvs.compactInternally(progress.getFullTableName());
            log.info("Finished performing compactInternally on {} in {} ms.", progress.getFullTableName(),
                    watch.elapsed(TimeUnit.MILLISECONDS));
        }

        // Truncate instead of delete because the progress table contains only
        // a single row that has accumulated many overwrites.
        kvs.truncateTable(tableFactory.getSweepProgressTable(t).getTableName());
    }
}

From source file:qa.qcri.nadeef.console.Console.java

private static void load(String cmdLine) throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    String[] splits = cmdLine.split("\\s");
    if (splits.length != 2) {
        console.println("Invalid load command. Run load <Nadeef config file>.");
        return;/* w  ww  .  ja va2  s .  co  m*/
    }
    String fileName = splits[1];
    File file = CommonTools.getFile(fileName);

    // shutdown existing executors
    for (CleanExecutor executor : executors) {
        executor.shutdown();
    }
    executors.clear();

    FileReader reader = null;
    try {
        reader = new FileReader(file);
        DBConfig dbConfig = NadeefConfiguration.getDbConfig();
        cleanPlans = CleanPlan.create(reader, dbConfig);
        for (CleanPlan cleanPlan : cleanPlans) {
            executors.add(new CleanExecutor(cleanPlan, dbConfig));
        }
    } catch (Exception ex) {
        tracer.err("Loading CleanPlan failed.", ex);
        return;
    } finally {
        if (reader != null)
            reader.close();
    }

    console.println(
            cleanPlans.size() + " rules loaded in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
    stopwatch.stop();
}