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:fr.xebia.management.statistics.ProfileAspectTest.java

@Test
public void testMaxActive_defaultSemaphoreAcquisition() throws Exception {
    // initialize
    testService.testMaxActiveSemaphoreAcquisition_default();

    String name = "test-max-active-semaphore-acquisition-default";
    ServiceStatistics serviceStatistics = profileAspect.serviceStatisticsByName.get(name);
    assertNotNull(serviceStatistics);//ww w . j  av a 2 s .  com
    assertEquals(TimeUnit.NANOSECONDS.convert(100, TimeUnit.MILLISECONDS),
            serviceStatistics.getMaxActiveSemaphoreAcquisitionMaxTimeInNanos());
}

From source file:com.linkedin.pinot.requestHandler.BrokerRequestHandler.java

public BrokerResponse handleRequest(JSONObject request) throws Exception {
    final String pql = request.getString("pql");
    final long requestId = _requestIdGenerator.incrementAndGet();
    LOGGER.debug("Query string for requestId {}: {}", requestId, pql);
    boolean isTraceEnabled = false;

    if (request.has("trace")) {
        try {/*w  ww.j a va  2s  . co m*/
            isTraceEnabled = Boolean.parseBoolean(request.getString("trace"));
            LOGGER.info("Trace is set to: {} for query {}", isTraceEnabled, pql);
        } catch (Exception e) {
            LOGGER.warn("Invalid trace value: {} for query {}", request.getString("trace"), pql, e);
        }
    } else {
        // ignore, trace is disabled by default
    }

    final long startTime = System.nanoTime();
    final BrokerRequest brokerRequest;
    try {
        brokerRequest = REQUEST_COMPILER.compileToBrokerRequest(pql);
        if (isTraceEnabled) {
            brokerRequest.setEnableTrace(true);
        }
        brokerRequest.setResponseFormat(ResponseType.BROKER_RESPONSE_TYPE_NATIVE.name());
    } catch (Exception e) {
        BrokerResponse brokerResponse = new BrokerResponseNative();
        brokerResponse
                .setExceptions(Arrays.asList(QueryException.getException(QueryException.PQL_PARSING_ERROR, e)));
        _brokerMetrics.addMeteredGlobalValue(BrokerMeter.REQUEST_COMPILATION_EXCEPTIONS, 1);
        LOGGER.info("Parsing error on query:{}", pql, e);
        return brokerResponse;
    }

    _brokerMetrics.addMeteredQueryValue(brokerRequest, BrokerMeter.QUERIES, 1);

    final long requestCompilationTime = System.nanoTime() - startTime;
    _brokerMetrics.addPhaseTiming(brokerRequest, BrokerQueryPhase.REQUEST_COMPILATION, requestCompilationTime);
    final ScatterGatherStats scatterGatherStats = new ScatterGatherStats();

    try {
        validateRequest(brokerRequest);
    } catch (Exception e) {
        BrokerResponse brokerResponse = new BrokerResponseNative();
        brokerResponse.setExceptions(
                Arrays.asList(QueryException.getException(QueryException.QUERY_VALIDATION_ERROR, e)));

        LOGGER.error("Validation error on query: {}", pql);
        return brokerResponse;
    }

    final BrokerResponse resp = _brokerMetrics.timeQueryPhase(brokerRequest, BrokerQueryPhase.QUERY_EXECUTION,
            new Callable<BrokerResponse>() {
                @Override
                public BrokerResponse call() throws Exception {
                    final BucketingSelection bucketingSelection = getBucketingSelection(brokerRequest);
                    return (BrokerResponse) processBrokerRequest(brokerRequest, bucketingSelection,
                            scatterGatherStats, requestId);
                }
            });

    // Query processing time is the total time spent in all steps include query parsing, scatter/gather, ser/de etc.
    long queryProcessingTimeInNanos = System.nanoTime() - startTime;
    long queryProcessingTimeInMillis = TimeUnit.MILLISECONDS.convert(queryProcessingTimeInNanos,
            TimeUnit.NANOSECONDS);
    resp.setTimeUsedMs(queryProcessingTimeInMillis);

    LOGGER.debug("Broker Response : {}", resp);
    LOGGER.info(
            "ResponseTimes for requestId:{}, table:{}, total time:{}, scanned docs:{}, total docs:{}, scatterGatherStats: {} query: {}",
            requestId, brokerRequest.getQuerySource().getTableName(), queryProcessingTimeInMillis,
            resp.getNumDocsScanned(), resp.getTotalDocs(), scatterGatherStats, pql);

    return resp;
}

From source file:fr.xebia.management.statistics.ServiceStatistics.java

@ManagedAttribute(description = "Total durations in millis of the invocations")
public long getTotalDurationInMillis() {
    return TimeUnit.MILLISECONDS.convert(getTotalDurationInNanos(), TimeUnit.NANOSECONDS);
}

From source file:com.linkedin.pinot.broker.requesthandler.BrokerRequestHandler.java

/**
 * Process a JSON format request./*from  w ww. jav a2  s . com*/
 *
 * @param request JSON format request to be processed.
 * @return broker response.
 * @throws Exception
 */
@Nonnull
public BrokerResponse handleRequest(@Nonnull JSONObject request) throws Exception {
    long requestId = _requestIdGenerator.incrementAndGet();
    String pql = request.getString("pql");
    LOGGER.debug("Query string for requestId {}: {}", requestId, pql);

    boolean isTraceEnabled = false;
    if (request.has("trace")) {
        isTraceEnabled = Boolean.parseBoolean(request.getString("trace"));
        LOGGER.debug("Trace is set to: {} for requestId {}: {}", isTraceEnabled, requestId, pql);
    }

    Map<String, String> debugOptions = null;
    if (request.has("debugOptions")) {
        String routingOptionParameter = request.getString("debugOptions");
        debugOptions = Splitter.on(';').omitEmptyStrings().trimResults().withKeyValueSeparator('=')
                .split(routingOptionParameter);
        LOGGER.debug("Debug options are set to: {} for requestId {}: {}", debugOptions, requestId, pql);
    }

    // Compile and validate the request.
    long compilationStartTime = System.nanoTime();
    BrokerRequest brokerRequest;
    try {
        brokerRequest = REQUEST_COMPILER.compileToBrokerRequest(pql);
    } catch (Exception e) {
        LOGGER.info("Parsing error on requestId {}: {}, {}", requestId, pql, e.getMessage());
        _brokerMetrics.addMeteredGlobalValue(BrokerMeter.REQUEST_COMPILATION_EXCEPTIONS, 1);
        return BrokerResponseFactory.getBrokerResponseWithException(DEFAULT_BROKER_RESPONSE_TYPE,
                QueryException.getException(QueryException.PQL_PARSING_ERROR, e));
    }
    String tableName = brokerRequest.getQuerySource().getTableName();
    try {
        validateRequest(brokerRequest);
    } catch (Exception e) {
        LOGGER.info("Validation error on requestId {}: {}, {}", requestId, pql, e.getMessage());
        _brokerMetrics.addMeteredTableValue(tableName, BrokerMeter.QUERY_VALIDATION_EXCEPTIONS, 1);
        return BrokerResponseFactory.getBrokerResponseWithException(DEFAULT_BROKER_RESPONSE_TYPE,
                QueryException.getException(QueryException.QUERY_VALIDATION_ERROR, e));
    }
    if (isTraceEnabled) {
        brokerRequest.setEnableTrace(true);
    }
    if (debugOptions != null) {
        brokerRequest.setDebugOptions(debugOptions);
    }
    brokerRequest.setResponseFormat(ResponseType.BROKER_RESPONSE_TYPE_NATIVE.name());
    _brokerMetrics.addPhaseTiming(tableName, BrokerQueryPhase.REQUEST_COMPILATION,
            System.nanoTime() - compilationStartTime);
    _brokerMetrics.addMeteredTableValue(tableName, BrokerMeter.QUERIES, 1);

    // Execute the query.
    long executionStartTime = System.nanoTime();
    ScatterGatherStats scatterGatherStats = new ScatterGatherStats();
    BrokerResponse brokerResponse = processBrokerRequest(brokerRequest, scatterGatherStats, requestId);
    _brokerMetrics.addPhaseTiming(tableName, BrokerQueryPhase.QUERY_EXECUTION,
            System.nanoTime() - executionStartTime);

    // Set total query processing time.
    long totalTimeMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - compilationStartTime,
            TimeUnit.NANOSECONDS);
    brokerResponse.setTimeUsedMs(totalTimeMs);

    LOGGER.debug("Broker Response: {}", brokerResponse);
    // Table name might have been changed (with suffix _OFFLINE/_REALTIME appended).
    LOGGER.info(
            "RequestId: {}, table: {}, totalTimeMs: {}, numDocsScanned: {}, numEntriesScannedInFilter: {}, "
                    + "numEntriesScannedPostFilter: {}, totalDocs: {}, scatterGatherStats: {}, query: {}",
            requestId, brokerRequest.getQuerySource().getTableName(), totalTimeMs,
            brokerResponse.getNumDocsScanned(), brokerResponse.getNumEntriesScannedInFilter(),
            brokerResponse.getNumEntriesScannedPostFilter(), brokerResponse.getTotalDocs(), scatterGatherStats,
            pql);

    return brokerResponse;
}

From source file:org.apache.hadoop.hbase.TestChoreService.java

@Test(timeout = 20000)
public void testScheduledChoreConstruction() {
    final String NAME = "chore";
    final int PERIOD = 100;
    final long VALID_DELAY = 0;
    final long INVALID_DELAY = -100;
    final TimeUnit UNIT = TimeUnit.NANOSECONDS;

    ScheduledChore chore1 = new ScheduledChore(NAME, new SampleStopper(), PERIOD, VALID_DELAY, UNIT) {
        @Override/*from ww  w .ja  v  a  2  s.co m*/
        protected void chore() {
            // DO NOTHING
        }
    };

    assertEquals("Name construction failed", chore1.getName(), NAME);
    assertEquals("Period construction failed", chore1.getPeriod(), PERIOD);
    assertEquals("Initial Delay construction failed", chore1.getInitialDelay(), VALID_DELAY);
    assertEquals("TimeUnit construction failed", chore1.getTimeUnit(), UNIT);

    ScheduledChore invalidDelayChore = new ScheduledChore(NAME, new SampleStopper(), PERIOD, INVALID_DELAY,
            UNIT) {
        @Override
        protected void chore() {
            // DO NOTHING
        }
    };

    assertEquals("Initial Delay should be set to 0 when invalid", 0, invalidDelayChore.getInitialDelay());
}

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

/**
 * Make sure can get the last update time of a file.
 *
 * @throws GenieException On error/* www.java2 s  .com*/
 */
@Test
public void canGetLastModifiedTimeIfNoHeader() throws GenieException {
    final long time = Instant.now().toEpochMilli() - 1;
    this.server.expect(MockRestRequestMatchers.requestTo(TEST_URL))
            .andExpect(MockRestRequestMatchers.method(HttpMethod.HEAD))
            .andRespond(MockRestResponseCreators.withSuccess());
    Assert.assertTrue(this.httpFileTransfer.getLastModifiedTime(TEST_URL) > time);
    Mockito.verify(this.metadataTimerId, Mockito.times(1)).withTags(MetricsUtils.newSuccessTagsMap());
    Mockito.verify(this.metadataTimer, Mockito.times(1)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));
}

From source file:com.netflix.spinnaker.front50.model.GcsStorageService.java

private <T> T timeExecute(Id timerId, AbstractGoogleClientRequest<T> request) throws IOException {
    T result;/* w  w w  . j  a  v  a  2  s .c om*/
    Clock clock = registry.clock();
    long startTime = clock.monotonicTime();
    int statusCode = -1;

    try {
        result = request.execute();
        statusCode = request.getLastStatusCode();
    } catch (HttpResponseException e) {
        statusCode = e.getStatusCode();
        throw e;
    } catch (IOException ioex) {
        throw ioex;
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    } finally {
        long nanos = clock.monotonicTime() - startTime;
        String status = Integer.toString(statusCode).charAt(0) + "xx";

        Id id = timerId.withTags("status", status, "statusCode", Integer.toString(statusCode));
        registry.timer(id).record(nanos, TimeUnit.NANOSECONDS);
    }
    return result;
}

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

public void run() throws IOException, InterruptedException {
    final long start = System.nanoTime();
    LOG.info("Starting indexer...");

    int numThreads = args.threads;

    final Directory dir = FSDirectory.open(indexPath);
    final EnglishAnalyzer analyzer = args.keepStopwords ? new EnglishAnalyzer(CharArraySet.EMPTY_SET)
            : new EnglishAnalyzer();
    final IndexWriterConfig config = new IndexWriterConfig(analyzer);
    config.setSimilarity(new BM25Similarity());
    config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    config.setRAMBufferSizeMB(args.memorybufferSize);
    config.setUseCompoundFile(false);//ww  w.  ja  v  a 2s  .c  o m
    config.setMergeScheduler(new ConcurrentMergeScheduler());

    final IndexWriter writer = new IndexWriter(dir, config);

    final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads);
    final List<Path> segmentPaths = collection.getFileSegmentPaths();

    final int segmentCnt = segmentPaths.size();
    LOG.info(segmentCnt + " files found in " + collectionPath.toString());
    for (int i = 0; i < segmentCnt; i++) {
        executor.execute(new IndexerThread(writer, collection, segmentPaths.get(i)));
    }

    executor.shutdown();

    try {
        // Wait for existing tasks to terminate
        while (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
            LOG.info(String.format("%.2f percent completed",
                    (double) executor.getCompletedTaskCount() / segmentCnt * 100.0d));
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        executor.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }

    if (segmentCnt != executor.getCompletedTaskCount()) {
        throw new RuntimeException("totalFiles = " + segmentCnt + " is not equal to completedTaskCount =  "
                + executor.getCompletedTaskCount());
    }

    int numIndexed = writer.maxDoc();

    try {
        writer.commit();
        if (args.optimize)
            writer.forceMerge(1);
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
            // It is possible that this happens... but nothing much we can do at this point,
            // so just log the error and move on.
            LOG.error(e);
        }
    }

    LOG.info("Indexed documents: " + counters.indexedDocuments.get());
    LOG.info("Empty documents: " + counters.emptyDocuments.get());
    LOG.info("Errors: " + counters.errors.get());

    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:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java

private int getBestNumber(String codeToExecute, boolean showResult, Message message) {
    for (int value = 0; value < 10;) {
        Double numberOfExecution = Math.pow(10, value);
        CompletableFuture<Boolean> keepLooking = new CompletableFuture<>();

        Long startTime = System.nanoTime();
        IntStream.range(0, numberOfExecution.intValue()).forEach(indexOfExecution -> {
            SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel,
                    new Message(new Header(message.type(), message.getHeader().getSession())), 0);
            if (!showResult) {
                simpleEvaluationObject.noResult();
            }//from  www  .j av a2s .c o  m

            kernel.executeCode(codeToExecute, simpleEvaluationObject);
            if (numberOfExecution.intValue() - 1 == indexOfExecution) {
                if (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime) > 0.2) {
                    keepLooking.complete(false);
                } else {
                    keepLooking.complete(true);
                }
            }
        });

        try {
            if (keepLooking.get()) {
                value++;
            } else {
                return numberOfExecution.intValue();
            }
        } catch (ExecutionException | InterruptedException e) {
            throw new IllegalStateException("Cannot create best number of execution.");
        }
    }

    throw new IllegalStateException("Cannot create best number of execution.");
}

From source file:com.linecorp.armeria.server.ServerTest.java

/**
 * Ensure that the connection is not broken even if {@link Service#serve(ServiceRequestContext, Request)}
 * raises an exception.// w w  w  .  java 2 s . com
 */
@Test(timeout = idleTimeoutMillis * 5)
public void testBuggyService() throws Exception {
    try (Socket socket = new Socket()) {
        socket.setSoTimeout((int) (idleTimeoutMillis * 4));
        socket.connect(server().activePort().get().localAddress());
        PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), false);

        // Send a request to a buggy service whose invoke() raises an exception.
        // If the server handled the exception correctly (i.e. responded with 500 Internal Server Error and
        // recovered from the exception successfully), then the connection should not be closed immediately
        // but on the idle timeout of the second request.
        outWriter.print("POST /buggy HTTP/1.1\r\n");
        outWriter.print("Connection: Keep-Alive\r\n");
        outWriter.print("Content-Length: 0\r\n");
        outWriter.print("\r\n");
        outWriter.print("POST / HTTP/1.1\r\n");
        outWriter.print("Connection: Keep-Alive\r\n");
        outWriter.print("\r\n");
        outWriter.flush();

        long lastWriteNanos = System.nanoTime();
        //read until EOF
        while (socket.getInputStream().read() != -1) {
            continue;
        }

        long elapsedTimeMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - lastWriteNanos,
                TimeUnit.NANOSECONDS);
        assertThat(elapsedTimeMillis, is(greaterThanOrEqualTo(idleTimeoutMillis)));
    }
}