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:me.oriley.crate.CrateGenerator.java

public boolean isCrateHashValid() {
    String crateOutputFile = mBaseOutputDir + '/' + PACKAGE_NAME.replace('.', '/') + "/" + CLASS_NAME + ".java";
    long startNanos = System.nanoTime();
    File file = new File(crateOutputFile);

    boolean returnValue = false;
    if (!file.exists()) {
        log("File " + crateOutputFile + " doesn't exist, hash invalid");
    } else if (!file.isFile()) {
        log("File " + crateOutputFile + " is not a file (?), hash invalid");
    } else {//  w  w  w . j  a v a  2 s. c o m
        returnValue = isFileValid(file, getComments());
    }

    long lengthMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
    log("Hash check took " + lengthMillis + "ms, was valid: " + returnValue);
    return returnValue;
}

From source file:rmblworx.tools.timey.SimpleTimerTest.java

/**
 * Test method for {@link SimpleTimer#toggleTimeModeInStopwatch()}.
 *
 * @throws InterruptedException/*from w w  w  . j ava  2  s . co  m*/
 *             wenn beim unterbrechen des Threads ein Ausnahme auftrat
 */
@Test
public final void testToggleTimeModeInStopwatchExtendedCase() throws InterruptedException {
    // testet ob TIME-Modus zuverlssig funktioniert wenn zwischendurch die Uhr gestoppt wurde whrend TIME-Modus
    // aktiv
    TimeDescriptor td = new TimeDescriptor(0L);
    this.timer = new SimpleTimer(td);
    this.timer.setApplicationContext(this.springContext);

    td = this.timer.startStopwatch(1, TimeUnit.NANOSECONDS);
    Thread.sleep(DELAY);
    assertTrue("Stoppuhr luft nicht!", td.getMilliSeconds() > 0);

    // TIME-Mode ein
    this.timer.toggleTimeModeInStopwatch();
    final long expected = td.getMilliSeconds();
    Thread.sleep(DELAY);
    long actual = td.getMilliSeconds();
    assertEquals("Stoppuhr zhlt weiter obwohl TIME-Mode aktiv!", expected, actual);

    // STOP gedrueckt - Zeitmessung stoppt aber eingefrorene Zeit bleibt im Vordergrund
    if (this.timer.stopStopwatch()) {
        assertEquals("Werte nicht identisch obwohl TIME-Mode aktiv!", expected, actual);
        actual = td.getMilliSeconds();
    } else {
        fail("Uhr konnte nicht angehalten werden!");
    }

    // TIME-Mode aus - Uhr noch angehalten - es muss nun der letzte Wert bei Stop geliefert werden
    this.timer.toggleTimeModeInStopwatch();
    Thread.sleep(1);
    actual = td.getMilliSeconds();
    assertNotEquals("Stoppuhr hat den TIME-Modus nicht deaktiviert!", expected, actual);
}

From source file:com.microsoft.rest.interceptors.LoggingInterceptor.java

@Override
public Response intercept(Chain chain) throws IOException {
    // get logger
    Request request = chain.request();
    String context = request.header(LOGGING_HEADER);
    if (context == null) {
        context = "";
    }/*from   w w  w  .  j av a2 s .c o  m*/
    Logger logger = LoggerFactory.getLogger(context);

    // log URL
    if (logLevel != LogLevel.NONE) {
        log(logger, String.format("--> %s %s", request.method(), request.url()));
    }
    // log headers
    if (logLevel == LogLevel.HEADERS || logLevel == LogLevel.BODY_AND_HEADERS) {
        for (String header : request.headers().names()) {
            if (!LOGGING_HEADER.equals(header)) {
                log(logger, String.format("%s: %s", header, Joiner.on(", ").join(request.headers(header))));
            }
        }
    }
    // log body
    if (logLevel == LogLevel.BODY || logLevel == LogLevel.BODY_AND_HEADERS) {
        if (request.body() != null) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);

            Charset charset = Charset.forName("UTF8");
            MediaType contentType = request.body().contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }

            if (isPlaintext(buffer)) {
                String content = buffer.clone().readString(charset);
                if (logLevel.isPrettyJson()) {
                    try {
                        content = MAPPER.writerWithDefaultPrettyPrinter()
                                .writeValueAsString(MAPPER.readValue(content, JsonNode.class));
                    } catch (Exception e) {
                        // swallow, keep original content
                    }
                }
                log(logger, String.format("%s-byte body:\n%s", request.body().contentLength(), content));
                log(logger, "--> END " + request.method());
            } else {
                log(logger, "--> END " + request.method() + " (binary " + request.body().contentLength()
                        + "-byte body omitted)");
            }
        }
    }

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        log(logger, "<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";

    // log URL
    if (logLevel != LogLevel.NONE) {
        log(logger, String.format("<-- %s %s %s (%s ms, %s body)", response.code(), response.message(),
                response.request().url(), tookMs, bodySize));
    }

    // log headers
    if (logLevel == LogLevel.HEADERS || logLevel == LogLevel.BODY_AND_HEADERS) {
        for (String header : response.headers().names()) {
            log(logger, String.format("%s: %s", header, Joiner.on(", ").join(response.headers(header))));
        }
    }

    // log body
    if (logLevel == LogLevel.BODY || logLevel == LogLevel.BODY_AND_HEADERS) {
        if (response.body() != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = Charset.forName("UTF8");
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(charset);
                } catch (UnsupportedCharsetException e) {
                    log(logger, "Couldn't decode the response body; charset is likely malformed.");
                    log(logger, "<-- END HTTP");
                    return response;
                }
            }

            boolean gzipped = response.header("content-encoding") != null
                    && StringUtils.containsIgnoreCase(response.header("content-encoding"), "gzip");
            if (!isPlaintext(buffer) && !gzipped) {
                log(logger, "<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                String content;
                if (gzipped) {
                    content = CharStreams
                            .toString(new InputStreamReader(new GZIPInputStream(buffer.clone().inputStream())));
                } else {
                    content = buffer.clone().readString(charset);
                }
                if (logLevel.isPrettyJson()) {
                    try {
                        content = MAPPER.writerWithDefaultPrettyPrinter()
                                .writeValueAsString(MAPPER.readValue(content, JsonNode.class));
                    } catch (Exception e) {
                        // swallow, keep original content
                    }
                }
                log(logger, String.format("%s-byte body:\n%s", buffer.size(), content));
            }
            log(logger, "<-- END HTTP");
        }
    }
    return response;
}

From source file:org.hawkular.apm.client.kafka.AbstractPublisherKafka.java

@Override
public void publish(String tenantId, List<T> items, int retryCount, long delay) throws Exception {
    // Check if delay is required
    // TODO: May need to check if delay is excessive and schedule message publish in separate thread
    if (delay > 0) {
        try {//  www  .  j av a2 s . com
            synchronized (this) {
                wait(delay);
            }
        } catch (Exception e) {
            // Ignore
        }
    }

    long startTime = 0;
    if (handler != null) {
        startTime = System.nanoTime();
    }

    for (int i = 0; i < items.size(); i++) {
        String data = mapper.writeValueAsString(items.get(i));
        // Sending record asynchronously without waiting for response. Failures
        // should be handled by Kafka's own retry mechanism, which has been
        // configured for 3 attempts (at 100ms intervals) by default
        producer.send(new ProducerRecord<String, String>(topic, data));
    }

    if (handler != null) {
        handler.published(tenantId, items, (TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - startTime)));
    }
}

From source file:io.anserini.index.IndexWebCollection.java

public static void main(String[] args) throws IOException, InterruptedException {

    IndexArgs indexArgs = new IndexArgs();

    CmdLineParser parser = new CmdLineParser(indexArgs, ParserProperties.defaults().withUsageWidth(90));

    try {// ww  w  . j  ava 2 s.  c  om
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.err.println("Example: IndexWebCollection" + parser.printExample(OptionHandlerFilter.REQUIRED));
        return;
    }

    final long start = System.nanoTime();
    IndexWebCollection indexer = new IndexWebCollection(indexArgs.input, indexArgs.index, indexArgs.collection);

    indexer.setPositions(indexArgs.positions);
    indexer.setOptimize(indexArgs.optimize);
    indexer.setDocLimit(indexArgs.doclimit);

    LOG.info("Index path: " + indexArgs.index);
    LOG.info("Threads: " + indexArgs.threads);
    LOG.info("Positions: " + indexArgs.positions);
    LOG.info("Optimize (merge segments): " + indexArgs.optimize);
    LOG.info("Doc limit: " + (indexArgs.doclimit == -1 ? "all docs" : "" + indexArgs.doclimit));

    LOG.info("Indexer: start");

    int numIndexed = indexer.indexWithThreads(indexArgs.threads);
    final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    LOG.info("Total " + numIndexed + " documents indexed in "
            + DurationFormatUtils.formatDuration(durationMillis, "HH:mm:ss"));
}

From source file:org.cleverbus.test.AbstractTest.java

/**
 * Initializes selected routes for specific test.
 * Active route definitions are defined via {@link ActiveRoutes} annotation.
 *
 * @throws Exception when init fails//from  w  ww .jav  a2 s  . c o m
 */
@Before
public void initRoutes() throws Exception {
    getCamelContext().getShutdownStrategy().setTimeout(1);// no shutdown timeout:
    getCamelContext().getShutdownStrategy().setTimeUnit(TimeUnit.NANOSECONDS);
    getCamelContext().getShutdownStrategy().setShutdownNowOnTimeout(true);// no pending exchanges

    Map<String, Class<RoutesBuilder>> beans = new HashMap<String, Class<RoutesBuilder>>();

    String[] beanNames = getApplicationContext().getBeanDefinitionNames();

    for (String beanName : beanNames) {
        Class beanClass = getApplicationContext().getType(beanName);

        if (beanClass.isAnnotationPresent(CamelConfiguration.class)) {
            beans.put(beanName, beanClass);
        }
    }

    Set<Class> activeRoutesClasses = getActiveRoutes();

    for (Map.Entry<String, Class<RoutesBuilder>> entry : beans.entrySet()) {

        for (Class routesClass : activeRoutesClasses) {

            if (entry.getValue().isAssignableFrom(routesClass)) {
                getCamelContext().addRoutes((RoutesBuilder) getApplicationContext().getBean(entry.getKey()));
            }
        }
    }
}

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

@Test
public void test() throws InterruptedException, ExecutionException {
    SLEEP_MS = 1000;/*  w  w w  . j  a  v a2 s .  c  om*/
    long startNs = System.nanoTime();
    try {
        LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
                TimeUnit.MILLISECONDS.toNanos(500)).get();
        fail();
    } catch (ExecutionException e) {
        e.printStackTrace();
        assertThat(e.getCause(), instanceOf(TimeoutIOException.class));
    }
    long costMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    assertTrue(costMs >= 500);
    assertTrue(costMs < 1000);
    // wait for the background task finish
    Thread.sleep(2000);
    // Now the location should be in cache, so we will not visit meta again.
    HRegionLocation loc = LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
            TimeUnit.MILLISECONDS.toNanos(500)).get();
    assertEquals(loc.getServerName(), TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName());
}

From source file:com.netflix.genie.web.services.impl.HttpFileTransferImpl.java

/**
 * {@inheritDoc}/* w w w.  java 2  s  . c om*/
 */
@Override
public void getFile(@NotBlank(message = "Source file path cannot be empty.") final String srcRemotePath,
        @NotBlank(message = "Destination local path cannot be empty") final String dstLocalPath)
        throws GenieException {
    final long start = System.nanoTime();
    log.debug("Called with src path {} and destination path {}", srcRemotePath, dstLocalPath);

    try {
        final File outputFile = new File(dstLocalPath);
        if (!this.isValid(srcRemotePath)) {
            throw new GenieServerException("Unable to download " + srcRemotePath + " not a valid URL");
        }
        this.restTemplate.execute(srcRemotePath, HttpMethod.GET,
                requestEntity -> requestEntity.getHeaders().setAccept(Lists.newArrayList(MediaType.ALL)),
                new ResponseExtractor<Void>() {
                    @Override
                    public Void extractData(final ClientHttpResponse response) throws IOException {
                        // Documentation I could find pointed to the HttpEntity reading the bytes off
                        // the stream so this should resolve memory problems if the file returned is large
                        FileUtils.copyInputStreamToFile(response.getBody(), outputFile);
                        return null;
                    }
                });
    } finally {
        this.downloadTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}

From source file:com.n0n3m4.q3e.Q3ECallbackObj.java

public void init(int size) {
    if (mAudioTrack != null)
        return;//from  w  w  w  .j  ava2  s  .  com
    if ((Q3EUtils.q3ei.isQ3) || (Q3EUtils.q3ei.isRTCW) || (Q3EUtils.q3ei.isQ1) || (Q3EUtils.q3ei.isQ2))
        size /= 8;

    mAudioData = new byte[size];
    int sampleFreq = 44100;

    /*                        _.---"'"""""'`--.._
                     _,.-'                   `-._
                 _,."                            -.
             .-""   ___...---------.._             `.
             `---'""                  `-.            `.
                                         `.            \
                                           `.           \
                                             \           \
                                              .           \
                                              |            .
                                              |            |
                        _________             |            |
                  _,.-'"         `"'-.._      :            |
              _,-'                      `-._.'             |
           _.'            OUYA               `.             '
      _.-.    _,+......__                           `.          .
    .'    `-"'           `"-.,-""--._                 \        /
    /    ,'                  |    __  \                 \      /
    `   ..                       +"  )  \                 \    /
    `.'  \          ,-"`-..    |       |                  \  /
    / " |        .'       \   '.    _.'                   .'
    |,.."--"""--..|    "    |    `""`.                     |
    ,"               `-._     |        |                     |
    .'                     `-._+         |                     |
    /                           `.                        /     |
    |    `     '                  |                      /      |
    `-.....--.__                  |              |      /       |
    `./ "| / `-.........--.-   '              |    ,'        '
    /| ||        `.'  ,'   .'               |_,-+         /
    / ' '.`.        _,'   ,'     `.          |   '   _,.. /
    /   `.  `"'"'""'"   _,^--------"`.        |    `.'_  _/
    /... _.`:.________,.'              `._,.-..|        "'
    `.__.'                                 `._  /
                                   "' */

    int bufferSize = Math.max((Q3EUtils.isOuya) ? 0 : 3 * size, AudioTrack.getMinBufferSize(sampleFreq,
            AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT));
    mAudioTrack = new Q3EAudioTrack(AudioManager.STREAM_MUSIC, sampleFreq,
            AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, bufferSize,
            AudioTrack.MODE_STREAM);
    mAudioTrack.play();
    long sleeptime = (size * 1000000000l) / (2 * 2 * sampleFreq);
    ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(5);
    stpe.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            if (reqThreadrunning) {
                Q3EJNI.requestAudioData();
            }
        }
    }, 0, sleeptime, TimeUnit.NANOSECONDS);
}

From source file:at.ac.univie.isc.asio.tool.Timeout.java

/**
 * Convert this timeout into a {@code String}. The text format is either {@code undefined} if the
 * timeout is not defined or the timeout value in milliseconds and {@code ms} appended.
 * The text representation of this timeout can be round-tripped via {@link #fromString(String)}.
 *
 * @return text value of this timeout/*from   w  w w .  j a v  a  2  s . c  o  m*/
 */
@JsonValue
@Override
public String toString() {
    final StringBuilder sb = new StringBuilder();
    if (isDefined()) {
        sb.append(Long.toString(TimeUnit.NANOSECONDS.toMillis(timeoutInNanos))).append("ms");
    } else {
        sb.append("undefined");
    }
    return sb.toString();
}