Example usage for java.lang System nanoTime

List of usage examples for java.lang System nanoTime

Introduction

In this page you can find the example usage for java.lang System nanoTime.

Prototype

@HotSpotIntrinsicCandidate
public static native long nanoTime();

Source Link

Document

Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.

Usage

From source file:com.l2jfree.lang.L2Thread.java

@Override
public final void run() {
    try {//  w w  w.  j  ava2 s .c  o  m
        while (_isAlive) {
            final long begin = System.nanoTime();

            try {
                runTurn();
            } finally {
                RunnableStatsManager.handleStats(getClass(), System.nanoTime() - begin);
            }

            try {
                sleepTurn();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } finally {
        onFinally();
    }
}

From source file:com.joyent.http.signature.apache.httpclient.HttpSignatureRequestInterceptor.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (!authEnabled) {
        return;//  www.  j  a  va2 s  . c o m
    }

    final long start = System.nanoTime();
    final Header authorization = authScheme.authenticate(this.credentials, request, context);
    final long end = System.nanoTime();

    request.setHeader(authorization);
    request.setHeader("x-http-signing-time-ns", String.valueOf(end - start));
}

From source file:apiserver.services.pdf.service.ProtectPdfCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    SecurePdfResult props = (SecurePdfResult) message.getPayload();
    File tmpFile = null;/*from w w w .  j  a  v a 2  s. c  o m*/

    try {
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<ByteArrayResult> future = exec
                .submit(new ProtectPdfCallable(props.getFile().getFileBytes(), props.getOptions()));

        ByteArrayResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getBytes());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    } finally {
        if (tmpFile != null)
            tmpFile.delete();
    }
}

From source file:org.commonjava.indy.ftest.core.content.SetContentTypeNotExistsTest.java

@Test
public void run() throws Exception {
    final String content = "This is some content " + System.currentTimeMillis() + "." + System.nanoTime();
    final String path = "org/foo/foo-project/1/foo-1.jar";

    server.expect("GET", server.formatUrl(STORE, path), (request, response) -> {
        response.setStatus(200);//w ww . j  ava2 s .  c  o  m
        response.setHeader("Content-Length", Integer.toString(content.length()));
        PrintWriter writer = response.getWriter();

        writer.write(content);
    });

    client.stores().create(new RemoteRepository(STORE, server.formatUrl(STORE)), "adding remote",
            RemoteRepository.class);

    try (HttpResources httpResources = client.module(IndyRawHttpModule.class).getHttp()
            .getRaw(client.content().contentPath(remote, STORE, path))) {
        HttpResponse response = httpResources.getResponse();

        String contentType = response.getFirstHeader("Content-Type").getValue();
        assertThat(contentType, equalTo(new MimetypesFileTypeMap().getContentType(path)));
    }
}

From source file:Main.java

/**
 * If the given time (based on {@link System#nanoTime}) has passed, throw a TimeoutException.
 * Otherwise, invoke {@link Object#wait(long, int)} on the given object, which may return due to
 * a {@code notify()} call, the timeout being reached, or a spurious wake-up.  To distinguish between
 * these possibilities, clients should wrap this call in a while loop:
 * {@code long t = futureTimeNanos(...); while (!condition) waitUntilNanos(lock, t);}
 * This loop either completes if the condition is satisfied or throws an appropriate exception
 * due to an interrupt or timeout./*from   w  w w .  ja  v a  2 s  . c  om*/
 * @param obj  Object whose {@code wait()} method will be invoked.  Must be locked by the current thread.
 * @param futureTime  A nanosecond time value based on {@code System.nanoTime()} after which
 *                    this method should no longer invoke {@code obj.wait()}.
 * @throws InterruptedException  If the wait is interrupted.
 * @throws TimeoutException  If, at invocation time, {@code futureTime} is in the past.
 * @see #futureTimeNanos
 */
public static void waitUntilNanos(Object obj, long futureTime) throws InterruptedException, TimeoutException {
    long delta = futureTime - System.nanoTime();
    if (delta > 0) {
        TimeUnit.NANOSECONDS.timedWait(obj, delta);
    } else {
        throw new TimeoutException();
    }
}

From source file:org.apache.sling.distribution.it.DistributionPackageExporterImporterTest.java

@Test
public void testDeleteExportImport() throws Exception {
    String nodePath = createRandomNode(publishClient, "/content/export_" + System.nanoTime());
    assertExists(publishClient, nodePath);

    String content = doExport(publish, "default", DistributionRequestType.DELETE, nodePath);

    doImport(publish, "default", content.getBytes(HTTP.DEFAULT_CONTENT_CHARSET));
    assertNotExists(publishClient, nodePath);
}

From source file:com.tecapro.inventory.common.util.LogUtil.java

/**
 * /*from  ww  w .  j  a  v  a 2s  .  c om*/
 * Start log output
 * 
 * @param log
 * @param clazz
 * @param method
 * @return
 */
public long startLog(Log log, String clazz, String method, InfoValue info) {

    long time = System.nanoTime();
    long totalMemory = Runtime.getRuntime().totalMemory();
    long freeMemory = Runtime.getRuntime().freeMemory();

    log.info(returnLogString(clazz, method, info, LogPrefix.START,
            new StringBuffer().append(totalMemory - freeMemory).append(",").append(totalMemory).toString()));

    Integer level = LOG_LEVEL.get(Thread.currentThread());

    if (level == null) {
        level = Integer.valueOf(1);
    } else {
        level += 1;
    }
    LOG_LEVEL.put(Thread.currentThread(), level);

    return time;

}

From source file:info.losd.galen.client.ApiClient.java

public ApiResponse execute(ApiRequest req) {
    try {/* www.  ja  va  2  s.co  m*/
        Request request = request(req);

        req.getHeaders().forEach((header, value) -> request.addHeader(header, value));

        long start = System.nanoTime();
        HttpResponse response = request.execute().returnResponse();
        long end = System.nanoTime();

        HealthcheckDetails stat = HealthcheckDetails.tag(req.getTag()).duration((end - start) / 1000000)
                .statusCode(response.getStatusLine().getStatusCode()).build();
        healthcheckRepo.save(stat);

        return ApiResponse.statusCode(response.getStatusLine().getStatusCode()).body(getResponseBody(response))
                .build();
    } catch (IOException e) {
        logger.error("IO Exception", e);
        throw new RuntimeException(e);
    }
}

From source file:com.produban.openbus.processor.function.PersistenceHDFS.java

@Override
public final void execute(final TridentTuple tuple, final TridentCollector collector) {
    String json = null;//from  ww  w .j a  v a  2s.  com
    try {
        json = (String) tuple.getStringByField("json");
        String datetimeInHour = FormatUtil.getDateFormat(tuple.getStringByField("datetime"),
                FormatUtil.DATE_FORMAT_WEBSERVER, FormatUtil.DATE_FORMAT_HOUR);

        hDFSStore.writeFile2HDFS(
                datetimeInHour + File.separator + "wslog" + "_" + datetimeInHour + "_" + System.nanoTime(),
                json);

        collector.emit(new Values(json));
    } catch (Exception e) {
        LOG.error("Persistence HDFS: " + json, e);
    }
}

From source file:com.ibm.og.client.CustomHttpEntity.java

@Override
public void writeTo(final OutputStream outstream) throws IOException {
    final InputStream in = getContent();
    OutputStream out = outstream;

    if (this.writeThroughput > 0) {
        out = Streams.throttle(outstream, this.writeThroughput);
    }/* w  w  w  . j  av a 2 s .co m*/

    this.requestContentStart = System.nanoTime();
    ByteStreams.copy(in, out);
    this.requestContentFinish = System.nanoTime();
    in.close();
}