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:org.apache.hadoop.hbase.client.TestAsyncRegionLocator.java

@Test
public void testTimeout() throws InterruptedException, ExecutionException {
    SLEEP_MS = 1000;/*from  w w  w  .  jav  a 2 s . co  m*/
    long startNs = System.nanoTime();
    try {
        LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
                TimeUnit.MILLISECONDS.toNanos(500)).get();
        fail();
    } catch (ExecutionException e) {
        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.hotelbeds.distribution.hotel_api_sdk.helpers.LoggingRequestInterceptor.java

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (!log.isInfoEnabled()) {
        return chain.proceed(request);
    } else {//from   w  w w  .j  a v a  2s . co m
        final RequestBody requestBody = request.body();
        final boolean hasRequestBody = requestBody != null;
        final Connection connection = chain.connection();
        final Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
        final StringBuilder requestInformation = new StringBuilder("Request: ");
        requestInformation.append(
                ObjectJoiner.join(" ", protocol.toString().toUpperCase(), request.method(), request.url()));
        long requestBodySize = -1;
        if (hasRequestBody) {
            requestBodySize = requestBody.contentLength();
            requestInformation.append(", body:");
            requestInformation.append(requestBodySize);
            requestInformation.append(" bytes");
        }
        log.info(requestInformation.toString());

        if (log.isDebugEnabled()) {
            // If the request has a body, sometimes these headers are not present, so let's make them explicit
            if (hasRequestBody) {
                if (requestBody.contentType() != null) {
                    logHeader(HotelApiClient.CONTENT_TYPE_HEADER, requestBody.contentType().toString());
                }
                if (requestBodySize != -1) {
                    logHeader(HotelApiClient.CONTENT_LENGTH_HEADER, Long.toString(requestBodySize));
                }
            }
            // Log the other headers
            for (String header : request.headers().names()) {
                if (!HotelApiClient.CONTENT_TYPE_HEADER.equalsIgnoreCase(header)
                        && !HotelApiClient.CONTENT_LENGTH_HEADER.equalsIgnoreCase(header)) {
                    for (String value : request.headers().values(header)) {
                        logHeader(header, value);
                    }
                }
            }
            if (log.isTraceEnabled() && hasRequestBody) {
                Supplier<Buffer> requestBufferSupplier = Unchecked.supplier(() -> {
                    Buffer buffer = new Buffer();
                    requestBody.writeTo(buffer);
                    return buffer;
                });
                logBody(requestBufferSupplier, requestBody.contentType(), request.headers());
            }
        }
        final long requestStart = System.nanoTime();
        final Response response = chain.proceed(request);
        final long totalRequestTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - requestStart);

        final ResponseBody responseBody = response.body();
        final long contentLength = responseBody.contentLength();

        log.info("Response: {}", ObjectJoiner.join(" ", response.code(), response.message()));
        if (contentLength >= 0) {
            log.info("  {}: {}", HotelApiClient.CONTENT_LENGTH_HEADER, contentLength);
        }
        log.info("  Request took {} ms", totalRequestTime);

        if (log.isDebugEnabled()) {
            for (String header : response.headers().names()) {
                for (String value : response.headers().values(header)) {
                    logHeader(header, value);
                }
            }
            if (log.isTraceEnabled() && HttpEngine.hasBody(response)) {
                MediaType contentType = responseBody.contentType();
                Supplier<Buffer> responseBufferSupplier = Unchecked.supplier(() -> {
                    BufferedSource source = responseBody.source();
                    source.request(Long.MAX_VALUE);
                    return source.buffer().clone();
                });
                logBody(responseBufferSupplier, contentType, response.headers());
            }
        }
        return response;
    }
}

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

/**
 * {@inheritDoc}//from w ww .j  a va2s.  c  om
 */
@Override
public void putFile(@NotBlank(message = "Source local path cannot be empty.") final String srcLocalPath,
        @NotBlank(message = "Destination remote path cannot be empty") final String dstRemotePath)
        throws GenieException {
    final long start = System.nanoTime();
    try {
        throw new UnsupportedOperationException(
                "Saving a file to an HttpEndpoint isn't implemented in this version");
    } finally {
        this.uploadTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}

From source file:org.apache.hadoop.mapred.gridmix.GridmixJob.java

protected GridmixJob(final Configuration conf, long submissionMillis, final String name) throws IOException {
    submissionTimeNanos = TimeUnit.NANOSECONDS.convert(submissionMillis, TimeUnit.MILLISECONDS);
    jobdesc = null;/*from  w  w  w .  j  a va 2 s  .  c o m*/
    outdir = null;
    seq = -1;
    ugi = UserGroupInformation.getCurrentUser();

    try {
        job = this.ugi.doAs(new PrivilegedExceptionAction<Job>() {
            public Job run() throws IOException {
                Job ret = new Job(conf, name);
                ret.getConfiguration().setInt("gridmix.job.seq", seq);
                setJobQueue(ret, conf.get(GRIDMIX_DEFAULT_QUEUE));

                return ret;
            }
        });
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:com.ebay.pulsar.sessionizer.cluster.SessionizerLoopbackRingListener.java

@Override
public <T> boolean isOwnershipChangedRecently(T affinityKey) {
    if (shutdownFlag || leavingCluster) {
        return false;
    }//ww  w .  j  av a  2  s.  c o m
    long currentNanoTime = System.nanoTime();
    if (head == null || (currentNanoTime - head.effectiveTime) > TimeUnit.NANOSECONDS
            .convert(getMaxIdleTime() + GRACE_PERIOD, TimeUnit.MILLISECONDS)) {
        return false;
    } else {
        EventConsumerInfo currentInfo = null;
        try {
            if (currentState.containsKey(loopbackTopic)) {
                ConsistentHashing<EventConsumerInfo> che = currentState.get(loopbackTopic);
                Object obj = affinityKey;
                if ((che != null) && (obj != null)) {
                    currentInfo = che.get(obj);
                }
            }
        } catch (Throwable t) {
        }

        if (currentInfo == null) {
            // Invalid state,
            return false;
        }
        return head.check(affinityKey, currentInfo, currentNanoTime);
    }
}

From source file:com.netflix.spectator.nflx.ChronosGcEventListener.java

private void sendToChronos(final byte[] json, final boolean blocking) {
    final URI uri = URI.create(CHRONOS_URI.get());

    final CountDownLatch latch = new CountDownLatch(1);
    final long start = System.nanoTime();
    rxHttp.postJson(uri, json).subscribe(new Action1<HttpClientResponse<ByteBuf>>() {
        @Override/*  w  w  w  .  ja v a 2s.  c om*/
        public void call(HttpClientResponse<ByteBuf> response) {
            final int code = response.getStatus().code();
            if (code != 200) {
                logger.warn("failed to send GC event to chronos (status={})", code);
            }
            final long latency = System.nanoTime() - start;
            final Id timerId = requestCount.withTag("status", "" + code);
            registry.timer(timerId).record(latency, TimeUnit.NANOSECONDS);
        }
    }, new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            logger.warn("failed to send GC event to chronos", t);
            final String status = t.getClass().getSimpleName();
            final long latency = System.nanoTime() - start;
            final Id timerId = requestCount.withTag("status", status);
            registry.timer(timerId).record(latency, TimeUnit.NANOSECONDS);
            latch.countDown();
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    // Used for unit tests so we can reliably detect completion
    if (blocking) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:edu.utah.further.ds.impl.advice.QpMonitorAdvice.java

@Override
public Object doAround(final ProceedingJoinPoint pjp, final ChainRequest request,
        final RequestProcessor requestProcessor) {
    printPreProcessorReport(request, requestProcessor);
    Object retVal = null;/* www .  ja va2 s.  c  om*/
    final long startTime = System.nanoTime();
    try {
        // Execute and time the processor
        retVal = pjp.proceed();
        final long durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);

        // Inject the proper status processor based the POST-request-processor query
        // state
        final QueryContext postQueryContext = request.getAttribute(QUERY_CONTEXT);
        final StatusType statusType = StatusType.valueOf(postQueryContext.isFailed());
        notifyStatus(request, requestProcessor, statusType, durationMillis);
        if (statusType.isFailed()) {
            // Change return value of the processor's method to terminate chain
            retVal = Boolean.TRUE;
        }
    } catch (final Throwable throwable) {
        final long durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
        // Take control of the request and execute a terminating processor; pass
        // the exception on to the status reporter
        request.setException(throwable);
        final QueryContext queryContext = request.getAttribute(QUERY_CONTEXT);
        final ResultContext resultContext = queryContext.getResultContext();
        if (throwable.getClass().isAssignableFrom(AccessDeniedException.class)) {
            resultContext.setNumRecords(ResultContext.ACCESS_DENIED);
        } else {
            // Override all errors to be -1 results so that partial results are not
            // displayed or zero is not displayed.
            resultContext.setNumRecords(-1);
        }

        final String exceptionString = getExceptionAsString(throwable);
        log.error("QpMonitorAdvice caught the following exception in processor " + requestProcessor.getName()
                + ": ", exceptionString);

        notifyStatus(request, requestProcessor, StatusType.FAIL, durationMillis);
        // Change return value of the processor's method to terminate chain
        retVal = Boolean.TRUE;
    }
    return retVal;
}

From source file:com.netflix.genie.web.tasks.leader.DatabaseCleanupTask.java

/**
 * Clean out database based on date.//  w  ww.  jav  a  2  s. com
 */
@Override
public void run() {
    final long start = System.nanoTime();
    final Map<String, String> tags = MetricsUtils.newSuccessTagsMap();
    try {
        final Calendar cal = TaskUtils.getMidnightUTC();
        // Move the date back the number of days retention is set for
        TaskUtils.subtractDaysFromDate(cal, this.cleanupProperties.getRetention());
        final Date retentionLimit = cal.getTime();
        final String retentionLimitString = this.dateFormat.format(retentionLimit);
        final int batchSize = this.cleanupProperties.getMaxDeletedPerTransaction();
        final int pageSize = this.cleanupProperties.getPageSize();

        log.info("Attempting to delete jobs from before {} in batches of {} jobs per iteration",
                retentionLimitString, batchSize);
        long totalDeletedJobs = 0;
        while (true) {
            final long numberDeletedJobs = this.jobPersistenceService
                    .deleteBatchOfJobsCreatedBeforeDate(retentionLimit, batchSize, pageSize);
            totalDeletedJobs += numberDeletedJobs;
            if (numberDeletedJobs == 0) {
                break;
            }
        }
        log.info("Deleted {} jobs from before {}", totalDeletedJobs, retentionLimitString);
        this.numDeletedJobs.set(totalDeletedJobs);
    } catch (Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        final long finish = System.nanoTime();
        this.registry.timer(deletionTimerId.withTags(tags)).record(finish - start, TimeUnit.NANOSECONDS);
    }
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java

/**
 * Constructor.//from  w w w  . j ava 2  s . c  om
 *
 * @param serverProperties The properties of the resource server (Genie)
 * @param converter        The access token converter to use
 * @param registry         The metrics registry to use
 */
public PingFederateRemoteTokenServices(@NotNull final ResourceServerProperties serverProperties,
        @NotNull final AccessTokenConverter converter, @NotNull final Registry registry) {
    super();
    this.tokenValidationError = registry
            .createId("genie.security.oauth2.pingFederate.tokenValidation.error.rate");
    this.authenticationTimer = registry.timer(AUTHENTICATION_TIMER_NAME);
    this.pingFederateAPITimer = registry.timer(API_TIMER_NAME);
    final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(2000);
    factory.setReadTimeout(10000);
    final RestTemplate restTemplate = new RestTemplate(factory);
    final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors
            .add((final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) -> {
                final long start = System.nanoTime();
                try {
                    return execution.execute(request, body);
                } finally {
                    pingFederateAPITimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
                }
            });
    restTemplate.setInterceptors(interceptors);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        // Ignore 400
        @Override
        public void handleError(final ClientHttpResponse response) throws IOException {
            final int errorCode = response.getRawStatusCode();
            registry.counter(tokenValidationError.withTag("status", Integer.toString(errorCode))).increment();
            if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) {
                super.handleError(response);
            }
        }
    });

    this.setRestTemplate(restTemplate);

    this.checkTokenEndpointUrl = serverProperties.getTokenInfoUri();
    this.clientId = serverProperties.getClientId();
    this.clientSecret = serverProperties.getClientSecret();

    Assert.state(StringUtils.isNotBlank(this.checkTokenEndpointUrl), "Check Endpoint URL is required");
    Assert.state(StringUtils.isNotBlank(this.clientId), "Client ID is required");
    Assert.state(StringUtils.isNotBlank(this.clientSecret), "Client secret is required");

    log.debug("checkTokenEndpointUrl = {}", this.checkTokenEndpointUrl);
    log.debug("clientId = {}", this.clientId);
    log.debug("clientSecret = {}", this.clientSecret);

    this.converter = converter;
}

From source file:org.apache.bookkeeper.mledger.impl.EntryCacheManager.java

boolean hasSpaceInCache() {
    long currentSize = this.currentSize.get();

    // Trigger a single eviction in background. While the eviction is running we stop inserting entries in the cache
    if (currentSize > evictionTriggerThreshold && evictionInProgress.compareAndSet(false, true)) {
        mlFactory.scheduledExecutor.execute(safeRun(() -> {
            // Trigger a new cache eviction cycle to bring the used memory below the cacheEvictionWatermark
            // percentage limit
            long sizeToEvict = currentSize - (long) (maxSize * cacheEvictionWatermak);
            long startTime = System.nanoTime();
            log.info("Triggering cache eviction. total size: {} Mb -- Need to discard: {} Mb", currentSize / MB,
                    sizeToEvict / MB);/*from ww  w .j  a v  a2  s.  c o m*/

            try {
                evictionPolicy.doEviction(Lists.newArrayList(caches.values()), sizeToEvict);

                long endTime = System.nanoTime();
                double durationMs = TimeUnit.NANOSECONDS.toMicros(endTime - startTime) / 1000.0;

                log.info("Eviction completed. Removed {} Mb in {} ms",
                        (currentSize - this.currentSize.get()) / MB, durationMs);
            } finally {
                mlFactoryMBean.recordCacheEviction();
                evictionInProgress.set(false);
            }
        }));
    }

    return currentSize < maxSize;
}