Example usage for java.util.concurrent TimeUnit NANOSECONDS

List of usage examples for java.util.concurrent TimeUnit NANOSECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit NANOSECONDS.

Prototype

TimeUnit NANOSECONDS

To view the source code for java.util.concurrent TimeUnit NANOSECONDS.

Click Source Link

Document

Time unit representing one thousandth of a microsecond.

Usage

From source file:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java

private void waitForServerStartup(StopWatch watch) throws UnknownHostException, IOException {
    Throwable lastCause = null;//from  w ww  . j a  v  a 2s  . c  o m
    final long start = System.nanoTime();
    final long maxWaitNs = TimeUnit.NANOSECONDS.convert(PG_STARTUP_WAIT_MS, TimeUnit.MILLISECONDS);
    while (System.nanoTime() - start < maxWaitNs) {
        try {
            checkReady();
            LOG.info("{} postmaster startup finished in {}", instanceId, watch);
            return;
        } catch (final SQLException e) {
            lastCause = e;
            LOG.trace("While waiting for server startup", e);
        }

        try {
            throw new IOException(
                    String.format("%s postmaster exited with value %d, check standard out for more detail!",
                            instanceId, postmaster.exitValue()));
        } catch (final IllegalThreadStateException e) {
            // Process is not yet dead, loop and try again
            LOG.trace("While waiting for server startup", e);
        }

        try {
            Thread.sleep(100);
        } catch (final InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
    }
    throw new IOException("Gave up waiting for server to start after " + PG_STARTUP_WAIT_MS + "ms", lastCause);
}

From source file:com.amazonaws.util.TimingInfo.java

public final Long getEndEpochTimeMilliIfKnown() {
    return isStartEpochTimeMilliKnown() && isEndTimeKnown()
            // make use of the wall clock time and elpased time
            ? startEpochTimeMilli.longValue()
                    + TimeUnit.NANOSECONDS.toMillis(endTimeNano.longValue() - startTimeNano)
            : null;/* w w w .  j a  v a  2s.  com*/
}

From source file:net.yacy.crawler.data.CacheTest.java

/**
 * Run a stress test on the Cache/*  w ww  .  ja  v  a 2  s  .c om*/
 * 
 * @param args
 *            main arguments
 * @throws IOException
 *             when a error occurred
 */
public static void main(final String args[]) throws IOException {
    System.out.println("Stress test on Cache");

    /*
     * Set the root log level to WARNING to prevent filling the console with
     * too many information log messages
     */
    LogManager.getLogManager().readConfiguration(
            new ByteArrayInputStream(".level=WARNING".getBytes(StandardCharsets.ISO_8859_1)));

    /* Main control parameters. Modify values for different scenarios. */

    /* Number of concurrent test tasks */
    final int threads = 50;
    /* Number of steps in each task */
    final int steps = 10;
    /* Number of test URLs in each task */
    final int urlsPerThread = 5;
    /* Size of the generated test content */
    final int contentSize = Math.max(Cache.DEFAULT_COMPRESSOR_BUFFER_SIZE + 1,
            Cache.DEFAULT_BACKEND_BUFFER_SIZE + 1) / urlsPerThread;
    /* Cache maximum size */
    final long cacheMaxSize = Math.min(1024 * 1024 * 1024, ((long) contentSize) * 10 * urlsPerThread);
    /* Sleep time between each cache operation */
    final long sleepTime = 0;
    /* Maximum waiting time (in ms) for acquiring a synchronization lock */
    final long lockTimeout = 2000;
    /* The backend compression level */
    final int compressionLevel = Deflater.BEST_COMPRESSION;

    Cache.init(new File(System.getProperty("java.io.tmpdir") + File.separator + "yacyTestCache"), "peerSalt",
            cacheMaxSize, lockTimeout, compressionLevel);
    Cache.clear();
    System.out.println("Cache initialized with a maximum size of " + cacheMaxSize + " bytes.");

    try {
        System.out.println("Starting " + threads + " threads ...");
        long time = System.nanoTime();
        List<CacheAccessTask> tasks = new ArrayList<>();
        for (int count = 0; count < threads; count++) {
            List<DigestURL> urls = new ArrayList<>();
            for (int i = 0; i < urlsPerThread; i++) {
                urls.add(new DigestURL("http://yacy.net/" + i + "/" + count));
            }
            CacheAccessTask thread = new CacheAccessTask(urls, steps, contentSize, sleepTime);
            thread.start();
            tasks.add(thread);
        }
        /* Wait for tasks termination */
        for (CacheAccessTask task : tasks) {
            try {
                task.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /*
         * Check consistency : cache should be empty when all tasks have
         * terminated without error
         */
        Cache.commit();
        long docCount = Cache.getActualCacheDocCount();
        if (docCount > 0) {
            System.out.println("Cache is not empty!!! Actual documents count : " + docCount);
        }

        System.out.println("All threads terminated in "
                + TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - time) + "s. Computing statistics...");
        long storeTime = 0;
        long maxStoreTime = 0;
        long getContentTime = 0;
        long maxGetContentTime = 0;
        int storeFailures = 0;
        long deleteTime = 0;
        long maxDeleteTime = 0;
        long totalSteps = 0;
        for (CacheAccessTask task : tasks) {
            storeTime += task.getStoreTime();
            maxStoreTime = Math.max(task.getMaxStoreTime(), maxStoreTime);
            getContentTime += task.getGetContentTime();
            maxGetContentTime = Math.max(task.getMaxGetContentTime(), maxGetContentTime);
            storeFailures += task.getStoreFailures();
            deleteTime += task.getDeleteTime();
            maxDeleteTime = Math.max(task.getMaxDeleteTime(), maxDeleteTime);
            totalSteps += task.getSteps();
        }
        System.out.println("Cache.store() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime));
        System.out.println("Cache.store() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxStoreTime));
        System.out.println(
                "Cache.store() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime / totalSteps));
        System.out.println("Cache.store() failures : " + storeFailures);
        System.out.println("");
        System.out.println(
                "Cache.getContent() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(getContentTime));
        System.out.println(
                "Cache.getContent() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxGetContentTime));
        System.out.println("Cache.getContent() mean time (ms) : "
                + TimeUnit.NANOSECONDS.toMillis(getContentTime / totalSteps));
        System.out.println("Cache hits : " + Cache.getHits() + " total requests : " + Cache.getTotalRequests()
                + " ( hit rate : " + NumberFormat.getPercentInstance().format(Cache.getHitRate()) + " )");
        System.out.println("");
        System.out.println("Cache.delete() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime));
        System.out
                .println("Cache.delete() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxDeleteTime));
        System.out.println(
                "Cache.delete() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime / totalSteps));
    } finally {
        try {
            Cache.close();
        } finally {
            /* Shutdown running threads */
            ArrayStack.shutdownDeleteService();
            try {
                Domains.close();
            } finally {
                ConcurrentLog.shutdown();
            }
        }
    }

}

From source file:com.clearspring.metriccatcher.MetricCatcher.java

/**
 * Update various metric types./* w w  w  .  j  ava  2  s.com*/
 *
 * Gauge:
 *
 * Counter:
 *     Increment or decrement based upon sign of value
 *     Clear counter if given 0
 *
 * Meter:
 *     mark() the meter with the given value
 *
 * Histogram:
 *     update() the histogram with the given value
 *
 * Timer:
 *
 * @param metric The metric to update
 * @param value The value to supply when updating the metric
 */
protected void updateMetric(Metric metric, double value) {
    if (metric instanceof Gauge) {
        ((GaugeMetricImpl) metric).setValue((long) value);
    } else if (metric instanceof Counter) {
        if (value > 0) {
            ((Counter) metric).inc((long) value);
        } else if (value < 0) {
            ((Counter) metric).dec((long) value * -1);
        } else {
            ((Counter) metric).clear();
        }
    } else if (metric instanceof Meter) {
        ((Meter) metric).mark((long) value);
    } else if (metric instanceof Histogram) {
        // TODO clearing?  How about no, so that we can record 0 values; it'll clear over time...
        ((Histogram) metric).update((long) value);
    } else if (metric instanceof Timer) {
        // Metrics Timer internally stores measurements as nanoseconds
        ((Timer) metric).update((long) (value * 1e9), TimeUnit.NANOSECONDS);
    } else {
        logger.debug("didn't find a class to map to");
    }
}

From source file:org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler.java

public boolean handleRequest(MessageContext messageContext) {
    Timer timer = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO,
            MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName()));
    Timer.Context context = timer.start();
    long executionStartTime = System.nanoTime();
    try {/*ww w. ja v a2s. com*/
        return doThrottle(messageContext);
    } finally {
        messageContext.setProperty(APIMgtGatewayConstants.THROTTLING_LATENCY,
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - executionStartTime));
        context.stop();
    }
}

From source file:com.cognifide.aet.runner.distribution.SuiteExecutor.java

private void process(ExecutionTimer timer) throws JMSException, AETException {
    if (tryProcess()) {
        checkStatusUntilFinishedOrTimedOut();
        if (comparisonResultsRouter.isFinished()) {
            timer.finish();/*from ww w .  ja  v  a2 s  .co m*/
            LOGGER.info("Finished lifecycle of test run: {}. Task finished in {} ms ({}).",
                    suite.get().getCorrelationId(), timer.getExecutionTimeInMillis(),
                    timer.getExecutionTimeInMMSS());
            LOGGER.info("Total tasks finished in steps: collect: {}; compare: {}.",
                    collectionResultsRouter.getTotalTasksCount(), comparisonResultsRouter.getTotalTasksCount());
        } else if (suiteIsTimedOut()) {
            timer.finish();
            LOGGER.warn(
                    "Lifecycle of run {} interrupted after {} ms ({}). Last message received: {} seconds ago... Trying to force report generation.",
                    suite.get().getCorrelationId(), timer.getExecutionTimeInMillis(),
                    timer.getExecutionTimeInMMSS(),
                    TimeUnit.NANOSECONDS.toSeconds(timeoutWatch.getLastUpdateDifference()));
            forceFinishSuite();
            collectDispatcher.cancel(suite.get().getCorrelationId());
        }
    }
}

From source file:com.netflix.genie.core.services.impl.S3FileTransferImpl.java

/**
 * {@inheritDoc}//from   w w  w .  j  a  v a2  s .  c  o m
 */
@Override
public long getLastModifiedTime(final String path) throws GenieException {
    final long start = System.nanoTime();
    final long lastModTime;
    final Map<String, String> tags = MetricsUtils.newSuccessTagsMap();
    try {
        final AmazonS3URI s3Uri = getS3Uri(path);
        try {
            final ObjectMetadata o = s3Client.getObjectMetadata(s3Uri.getBucket(), s3Uri.getKey());
            lastModTime = o.getLastModified().getTime();
        } catch (final Exception ase) {
            final String message = String.format("Failed getting the metadata of the s3 file %s", path);
            log.error(message);
            throw new GenieServerException(message, ase);
        }
    } catch (Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.registry.timer(getTimerId.withTags(tags)).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
    return lastModTime;
}

From source file:org.agatom.springatom.web.NewCarWizardProcessor.java

@Override
protected WizardResult submitStep(final NCar contextObject, final ModelMap stepData, final String step,
        final Locale locale) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("submitStep(contextObject=%s)", contextObject));
    }/*from   w ww.j  a  v a 2  s .c  o  m*/

    final WizardResult result = new WizardResult();

    if (this.steps.VIN.getStep().equals(step)) {
        final long startTime = System.nanoTime();
        final String vinNumber = contextObject.getVinNumber();

        try {
            final VinNumberData decode = this.vinDecoder.decode(vinNumber);
            result.addWizardData("years",
                    selectComponentFactory.<Integer, Integer, Integer>newSelectComponent()
                            .from(decode.getYears()).usingLabelFunction(Functions.<Integer>identity())
                            .usingValueFunction(Functions.<Integer>identity()).get().getOptions());
            result.addFormData("manufacturedIn", decode.getManufacturedIn());
            result.addStepData("vinNumberData", decode);

        } catch (VinDecodingException | ComponentCompilationException e) {
            LOGGER.error(String.format("Vin decoding failed, for vinNumber=%s", vinNumber), e);
            result.addError(e);
        }

        final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("submitStep(contextObject=%s) took %d ms", contextObject, endTime));
        }

        result.addDebugData(WizardDebugDataKeys.SUBMISSION_TIME, endTime);
    }

    return result;
}

From source file:at.alladin.rmbt.android.test.RMBTTask.java

private void doInBackground() {
    try {//from   w  w w .  j a  v a2s.  co  m
        boolean error = false;
        connectionError.set(false);
        TestResult result = null;
        QoSResultCollector qosResult = null;

        try {
            final String uuid = fullInfo.getUUID();

            final String controlServer = ConfigHelper.getControlServerName(context);
            final int controlPort = ConfigHelper.getControlServerPort(context);
            final boolean controlSSL = ConfigHelper.isControlSeverSSL(context);

            final ArrayList<String> geoInfo = fullInfo.getCurLocation();

            client = RMBTClient.getInstance(controlServer, null, controlPort, controlSSL, geoInfo, uuid,
                    Config.RMBT_CLIENT_TYPE, Config.RMBT_CLIENT_NAME,
                    fullInfo.getInfo("CLIENT_SOFTWARE_VERSION"), null, fullInfo.getInitialInfo());

            if (client != null) {
                /*
                 * Example on how to implement the information collector tool:
                 *
                 * 
                */

                final InformationCollectorTool infoTool = new InformationCollectorTool(TimeUnit.NANOSECONDS,
                        TimeUnit.NANOSECONDS.convert(120, TimeUnit.SECONDS));
                infoTool.addCollector(new CpuStatCollector(new CpuStatAndroidImpl(),
                        TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS)));
                infoTool.addCollector(new MemInfoCollector(new MemInfoAndroidImpl(),
                        TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS)));
                client.setInformationCollectorTool(infoTool);
                client.startInformationCollectorTool();

                /////////////////////////////////////////////////////////////////

                client.setTrafficService(new TrafficServiceImpl());
                final ControlServerConnection controlConnection = client.getControlConnection();
                if (controlConnection != null) {
                    fullInfo.setUUID(controlConnection.getClientUUID());
                    fullInfo.setTestServerName(controlConnection.getServerName());
                }
            }
        } catch (final Exception e) {
            e.printStackTrace();
            error = true;
        }

        if (error || client == null) {
            connectionError.set(true);
        } else {

            if (client.getStatus() != TestStatus.ERROR) {
                try {
                    if (Thread.interrupted() || cancelled.get())
                        throw new InterruptedException();
                    Log.d(LOG_TAG, "runTest RMBTTask=" + this);
                    result = client.runTest();
                    final ControlServerConnection controlConnection = client.getControlConnection();

                    final InformationCollectorTool infoCollectorTool = client.getInformationCollectorTool();

                    if (result != null && !fullInfo.getIllegalNetworkTypeChangeDetcted()) {
                        final JSONObject infoObject = fullInfo
                                .getResultValues(controlConnection.getStartTimeNs());
                        if (infoCollectorTool != null) {
                            infoCollectorTool.stop();
                            infoObject.put("extended_test_stat", infoCollectorTool.getJsonObject(true,
                                    client.getControlConnection().getStartTimeNs()));
                        }

                        infoObject.put("publish_public_data", ConfigHelper.isInformationCommissioner(context));

                        client.sendResult(infoObject);
                    } else {
                        error = true;
                    }
                } catch (final Exception e) {
                    e.printStackTrace();
                } finally {
                    client.shutdown();
                }
            } else {
                System.err.println(client.getErrorMsg());
                error = true;
            }

            //client.shutdown();

            setPreviousTestStatus();
            QualityOfServiceTest qosTest = null;

            boolean runQoS = (client.getTaskDescList() != null && client.getTaskDescList().size() >= 1);

            //run qos test:
            if (runQoS && !error && !cancelled.get()) {
                try {

                    TestSettings qosTestSettings = new TestSettings();
                    qosTestSettings.setCacheFolder(context.getCacheDir());
                    qosTestSettings.setWebsiteTestService(new WebsiteTestServiceImpl(context));
                    qosTestSettings.setTrafficService(new TrafficServiceImpl());
                    qosTestSettings.setTracerouteServiceClazz(TracerouteAndroidImpl.class);
                    qosTestSettings.setStartTimeNs(getRmbtClient().getControlConnection().getStartTimeNs());
                    qosTestSettings.setUseSsl(ConfigHelper.isQoSSeverSSL(context));

                    qosTest = new QualityOfServiceTest(client, qosTestSettings);
                    qosReference.set(qosTest);
                    client.setStatus(TestStatus.QOS_TEST_RUNNING);
                    qosResult = qosTest.call();
                    InformationCollector.qoSResult = qosResult;

                    if (!cancelled.get()) {
                        if (qosResult != null && !qosTest.getStatus().equals(QoSTestEnum.ERROR)) {
                            client.sendQoSResult(qosResult);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    error = true;
                }
            }

            if (qosTest != null && !cancelled.get() && qosTest.getStatus().equals(QoSTestEnum.QOS_FINISHED)) {
                if (ConfigHelper.isNDT(context)) {
                    qosTest.setStatus(QoSTestEnum.NDT_RUNNING);
                    runNDT();
                }
                qosTest.setStatus(QoSTestEnum.STOP);
            }
        }
    } catch (final Exception e) {
        client.setStatus(TestStatus.ERROR);
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        try {
            if (client != null) {
                client.stopInformationCollectorTool();
                final TestStatus status = client.getStatus();
                if (!(status == TestStatus.ABORTED || status == TestStatus.ERROR))
                    client.setStatus(TestStatus.END);
            }
        } catch (Exception e) {
        }
    }
}

From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java

private <T> MasterRequestCallerBuilder<T> newMasterCaller() {
    return this.connection.callerFactory.<T>masterRequest().rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
            .operationTimeout(operationTimeoutNs, TimeUnit.NANOSECONDS).pause(pauseNs, TimeUnit.NANOSECONDS)
            .maxAttempts(maxAttempts).startLogErrorsCnt(startLogErrorsCnt);
}