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

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

Introduction

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

Prototype

@CheckReturnValue
public static Stopwatch createStarted() 

Source Link

Document

Creates (and starts) a new stopwatch using System#nanoTime as its time source.

Usage

From source file:nl.knaw.huygens.timbuctoo.storage.graph.tinkerpop.TinkerPopIterator.java

@Override
public List<T> getSome(int limit) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    LOG.debug("Get some started");
    List<T> some = Lists.newArrayList();
    for (; limit > 0 && hasNext(); limit--) {
        some.add(next());/*from  ww  w .ja v  a  2s  . c  o  m*/
    }
    LOG.debug("Get some ended in [{}]", stopwatch.stop());

    return some;
}

From source file:com.google.gerrit.server.index.account.AllAccountsIndexer.java

@Override
public SiteIndexer.Result indexAll(final AccountIndex index) {
    ProgressMonitor progress = new TextProgressMonitor(new PrintWriter(progressOut));
    progress.start(2);//from w  w  w .j av  a2 s.  c  om
    Stopwatch sw = Stopwatch.createStarted();
    List<Account.Id> ids;
    try {
        ids = collectAccounts(progress);
    } catch (OrmException e) {
        log.error("Error collecting accounts", e);
        return new SiteIndexer.Result(sw, false, 0, 0);
    }
    return reindexAccounts(index, ids, progress);
}

From source file:org.apache.brooklyn.util.net.Networking.java

public static boolean isPortAvailable(InetAddress localAddress, int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }/*w  ww  .j  ava  2  s  .com*/

    Stopwatch watch = Stopwatch.createStarted();
    try {
        //despite http://stackoverflow.com/questions/434718/sockets-discover-port-availability-using-java
        //(recommending the following) it isn't 100% reliable (e.g. nginx will happily coexist with ss+ds)
        //
        //Svet - SO_REUSEADDR (enabled below) will allow one socket to listen on 0.0.0.0:X and another on
        //192.168.0.1:X which explains the above comment (nginx sets SO_REUSEADDR as well). Moreover there
        //is no TIME_WAIT for listening sockets without any connections so why enable it at all.
        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            // Check TCP port
            ss = new ServerSocket();
            ss.setSoTimeout(250);
            ss.setReuseAddress(true);
            ss.bind(new InetSocketAddress(localAddress, port));

            // Check UDP port
            ds = new DatagramSocket(null);
            ds.setSoTimeout(250);
            ds.setReuseAddress(true);
            ds.bind(new InetSocketAddress(localAddress, port));
        } catch (IOException e) {
            if (log.isTraceEnabled())
                log.trace("Failed binding to " + localAddress + " : " + port, e);
            return false;
        } finally {
            closeQuietly(ds);
            closeQuietly(ss);
        }

        if (localAddress == null || ANY_NIC.equals(localAddress)) {
            // sometimes 0.0.0.0 can be bound to even if 127.0.0.1 has the port as in use;
            // check all interfaces if 0.0.0.0 was requested
            Enumeration<NetworkInterface> nis = null;
            try {
                nis = NetworkInterface.getNetworkInterfaces();
            } catch (SocketException e) {
                throw Exceptions.propagate(e);
            }
            // When using a specific interface saw failures not caused by port already bound:
            //   * java.net.SocketException: No such device
            //   * java.net.BindException: Cannot assign requested address
            //   * probably many more
            // Check if the address is still valid before marking the port as not available.
            boolean foundAvailableInterface = false;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                Enumeration<InetAddress> as = ni.getInetAddresses();
                while (as.hasMoreElements()) {
                    InetAddress a = as.nextElement();
                    if (!isPortAvailable(a, port)) {
                        if (isAddressValid(a)) {
                            if (log.isTraceEnabled())
                                log.trace("Port {} : {} @ {} is taken and the address is valid",
                                        new Object[] { a, port, nis });
                            return false;
                        }
                    } else {
                        foundAvailableInterface = true;
                    }
                }
            }
            if (!foundAvailableInterface) {
                //Aborting with an error, even nextAvailablePort won't be able to find a free port.
                throw new RuntimeException(
                        "Unable to bind on any network interface, even when letting the OS pick a port. Possible causes include file handle exhaustion, port exhaustion. Failed on request for "
                                + localAddress + ":" + port + ".");
            }
        }

        return true;
    } finally {
        // Until timeout was added, was taking 1min5secs for /fe80:0:0:0:1cc5:1ff:fe81:a61d%8 : 8081
        // Svet - Probably caused by the now gone new Socket().connect() call, SO_TIMEOUT doesn't
        // influence bind(). Doesn't hurt having it though.
        long elapsed = watch.elapsed(TimeUnit.SECONDS);
        boolean isDelayed = (elapsed >= 1);
        boolean isDelayedByMuch = (elapsed >= 30);
        if (isDelayed || log.isTraceEnabled()) {
            String msg = "Took {} to determine if port was available for {} : {}";
            Object[] args = new Object[] { Time.makeTimeString(watch.elapsed(TimeUnit.MILLISECONDS), true),
                    localAddress, port };
            if (isDelayedByMuch) {
                log.warn(msg, args);
            } else if (isDelayed) {
                log.debug(msg, args);
            } else {
                log.trace(msg, args);
            }
        }
    }
}

From source file:org.ow2.proactive.resourcemanager.core.NodesLockRestorationManager.java

protected void initialize() {
    Stopwatch stopwatch = null;/*from   ww  w  .j a v  a 2s  .  co  m*/

    if (log.isInfoEnabled()) {
        stopwatch = Stopwatch.createStarted();
    }

    nodeLockedOnPreviousRun = findNodesLockedOnPreviousRun();

    if (log.isInfoEnabled()) {
        stopwatch.stop();
        log.info("Identifying nodes locked on the previous run required "
                + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
    }

    if (nodeLockedOnPreviousRun.isEmpty()) {
        log.info("There is no locks to restore");
    } else {
        log.info("Here is the number of nodes to lock per node source:");

        for (Map.Entry<String, MutableInteger> entry : nodeLockedOnPreviousRun.entrySet()) {
            log.info("  - nodeSource=" + entry.getKey() + ", host=" + entry.getKey() + ", count="
                    + entry.getValue().getValue());
        }
    }

    initialized = true;
}

From source file:com.facebook.buck.log.TimedLogger.java

private void timedLogCalled(Consumer<String> logFunction, String rawLogMessage) {
    int logRequestId = this.currentLogRequestId.incrementAndGet();
    String logMessageWithId = String.format("%s [Log ID: %d]", rawLogMessage, logRequestId);

    Stopwatch stopwatch = Stopwatch.createStarted();
    logFunction.accept(logMessageWithId);
    long logCallDurationMillis = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    if (logCallDurationMillis > maxLogCallDurationMillis) {
        delegate.warn(String.format(
                ("Log request with ID [%d] took [%d] milliseconds, "
                        + "which is longer than threshold of [%d] milliseconds."),
                logRequestId, logCallDurationMillis, maxLogCallDurationMillis));
    }/*from www.j  a  v  a 2  s.  c  o  m*/
}

From source file:flipkart.lego.engine.filters.FilterChain.java

/**
 * Processes a given filter chain and returns remaining time for timeout
 *
 * @param request//from w w  w .j av a2s .  co  m
 * @param response
 * @param filterExecutionPhase
 * @param remainingTime
 * @return remaining time for timeout after filter processing
 * @throws java.util.concurrent.TimeoutException
 * @throws flipkart.lego.api.exceptions.InternalErrorException
 * @throws flipkart.lego.api.exceptions.BadRequestException
 * @throws flipkart.lego.api.exceptions.ProcessingException
 */
public long process(Request request, Response response, FilterExecutionPhase filterExecutionPhase,
        long remainingTime)
        throws TimeoutException, InternalErrorException, BadRequestException, ProcessingException {
    Stopwatch filterChainStopwatch = Stopwatch.createStarted();

    Future filterProcessing = this.filterTPE
            .submit(new FilterChainExecutor(this, filterExecutionPhase, request, response));

    try {
        filterProcessing.get(remainingTime, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        filterProcessing.cancel(true);
        exceptionLogger.error("Filter Processing timed out: ", filterChain);
        throw new TimeoutException("Timed out while executing filterChain");
    } catch (ExecutionException e) {
        filterProcessing.cancel(true);
        if (e.getCause() instanceof InternalErrorException) {
            exceptionLogger.error("InternalErrorException when processing filters", filterChain);
            throw (InternalErrorException) e.getCause();
        } else if (e.getCause() instanceof BadRequestException) {
            exceptionLogger.error("BadRequestException when processing filters", filterChain);
            throw (BadRequestException) e.getCause();
        } else if (e.getCause() instanceof ProcessingException) {
            throw (ProcessingException) e.getCause();
        } else {
            exceptionLogger.error("Execution Exception when processing filters", filterChain);
            throw new InternalErrorException(e);
        }
    }

    filterChainStopwatch.stop();
    return remainingTime - filterChainStopwatch.elapsed(TimeUnit.MILLISECONDS);
}

From source file:de.schildbach.wallet.data.AddressBookProvider.java

@Override
public boolean onCreate() {
    final Stopwatch watch = Stopwatch.createStarted();

    final Context context = getContext();
    Logging.init(context.getFilesDir());
    helper = new Helper(context);

    watch.stop();/*from   ww w  .j a  v a  2  s.  c  om*/
    log.info("{}.onCreate() took {}", getClass().getSimpleName(), watch);
    return true;
}

From source file:uk.ac.ebi.atlas.search.baseline.BaselineExpressionDao.java

public ImmutableList<BaselineExperimentExpression> fetchAverageExpressionByExperimentAssayGroup(
        final Collection<String> geneIds) {
    if (geneIds.isEmpty()) {
        return ImmutableList.of();
    }/* ww w  .  j  a va2  s. c  om*/

    LOGGER.debug(String.format("fetchAverageExpressionByExperimentAssayGroup for %s genes", geneIds.size()));

    Stopwatch stopwatch = Stopwatch.createStarted();

    try {

        DatabaseQuery<Object> baselineExpressionQuery = buildSelect(geneIds);

        final ImmutableList.Builder<BaselineExperimentExpression> builder = ImmutableList.builder();

        final MutableInt numberOfGenesExpressedInCurrentExperiment = new MutableInt(0);

        jdbcTemplate.query(baselineExpressionQuery.getQuery(), new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                String experimentAccession = rs.getString(BaselineQueryBuilder.EXPERIMENT);
                String assayGroupId = rs.getString(BaselineQueryBuilder.ASSAY_GROUP_ID);

                if (assayGroupId == null) {
                    // every-time we see a null assaygroupid, this is the beginning of rows for another experiment
                    // and this row will contain the experiment level totals
                    double numberOfGenesExpressed = rs.getInt(BaselineQueryBuilder.NUMBER_GENES_EXPRESSED);
                    numberOfGenesExpressedInCurrentExperiment.setValue(numberOfGenesExpressed);
                    return;
                }

                double expression = baselineExpressionLevelRounder
                        .round(rs.getDouble(BaselineQueryBuilder.EXPRESSION)
                                / numberOfGenesExpressedInCurrentExperiment.intValue());
                BaselineExperimentExpression bslnExpression = BaselineExperimentExpression
                        .create(experimentAccession, assayGroupId, expression);

                builder.add(bslnExpression);
            }
        }, baselineExpressionQuery.getParameters().toArray());

        ImmutableList<BaselineExperimentExpression> results = builder.build();

        stopwatch.stop();
        LOGGER.debug(String.format(
                "fetchAverageExpressionByExperimentAssayGroup returned %s results in %.2f seconds",
                results.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000D));
        return results;

    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw e;
    }

}

From source file:qa.qcri.nadeef.core.pipeline.UpdateExecutor.java

public void run() {
    Stopwatch sw = Stopwatch.createStarted();
    updateFlow.reset();/*from w  ww  .  j ava2s  .  c o m*/
    updateFlow.start();
    updateFlow.waitUntilFinish();

    PerfReport.appendMetric(PerfReport.Metric.EQTime, sw.elapsed(TimeUnit.MILLISECONDS));
    sw.stop();
}

From source file:io.ecarf.core.cloud.task.processor.dictionary.AssembleDictionarySubTask.java

@SuppressWarnings("unchecked")
@Override/*from  w  w w.  j  a  v a2  s .  co m*/
public Void call() throws Exception {

    for (Item item : this.files) {

        String file = item.getKey();

        String localFile = FilenameUtils.getLocalFilePath(file);

        log.info("START: Downloading file: " + file + ", memory usage: " + Utils.getMemoryUsageInGB() + "GB");
        Stopwatch stopwatch = Stopwatch.createStarted();

        try {

            this.downloadFile(file, localFile, 1);

            // all downloaded, carryon now, process the files
            log.info("Processing file: " + localFile + ", dictionary items: " + dictionary.size()
                    + ", memory usage: " + Utils.getMemoryUsageInGB() + "GB" + ", timer: " + stopwatch);

            Set<String> parts = Utils.objectFromFile(localFile, HashSet.class, true, false);

            log.info("Processing: " + parts.size() + " term parts , memory usage: " + Utils.getMemoryUsageInGB()
                    + "GB" + ", timer: " + stopwatch);

            for (String part : parts) {
                dictionary.add(part);
            }

            // immediately release parts
            parts = null;

            log.info("TIMER# Finished processing file: " + localFile + ", memory usage: "
                    + Utils.getMemoryUsageInGB() + "GB" + ", timer: " + stopwatch);
            log.info("Dictionary size: " + dictionary.size());

            FileUtils.deleteFile(localFile);

        } catch (Exception e) {
            // because this sub task is run in an executor the exception will be stored and thrown in the
            // future, but we want to know about it now, so log it
            log.error("Failed to download or process file: " + file, e);

            if (e instanceof IOException) {
                throw e;
            } else {
                throw new IOException(e);
            }
        }
    }

    return null;
}