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.couchbase.shell.CouchbaseBucketCommands.java

@CliCommand(value = GETPING, help = "Retreive a document from the server for a perioud and count the time.")
public String getping(
        @CliOption(mandatory = true, key = { "",
                "key" }, help = "The unique name of the key in this bucket") String key,
        @CliOption(key = "runs", help = "The number of pings to perform", unspecifiedDefaultValue = "10") String runs,
        @CliOption(key = "delay", help = "Time to sleep between pings", unspecifiedDefaultValue = "0") String delay) {
    try {//w w  w.ja va  2s  .  c o m
        int totalRuns = Integer.parseInt(runs);
        int del = Integer.parseInt(delay);

        StringBuilder builder = new StringBuilder();
        long total = 0;
        long totalMin = Integer.MAX_VALUE;
        long totalMax = Integer.MIN_VALUE;
        for (int i = 0; i < totalRuns; i++) {
            long start = System.nanoTime();
            OperationFuture<CASValue<Object>> future = shell.get(key);
            future.get();
            long end = System.nanoTime();
            builder.append(formatStatusLine(future.getStatus()));
            CASValue<Object> data = future.get();
            if (future.getStatus().isSuccess()) {
                builder.append(", CAS: " + data.getCas());
            }
            long diff = end - start;
            total += diff;
            builder.append(", Time: " + TimeUnit.NANOSECONDS.toMicros(diff) + "s");
            if (diff < totalMin) {
                totalMin = diff;
            }
            if (diff > totalMax) {
                totalMax = diff;
            }
            builder.append("\n");
            Thread.sleep(del);
        }
        builder.append("Total: " + TimeUnit.NANOSECONDS.toMicros(total) + "s");
        builder.append(", Average: " + TimeUnit.NANOSECONDS.toMicros(total / totalRuns) + "s");
        builder.append(", Min: " + TimeUnit.NANOSECONDS.toMicros(totalMin) + "s");
        builder.append(", Max: " + TimeUnit.NANOSECONDS.toMicros(totalMax) + "s");
        return builder.toString();
    } catch (Exception ex) {
        return "Could not get document " + key + " because of an error! ";
    }
}

From source file:co.paralleluniverse.galaxy.core.BackupImpl.java

public void setMaxDelay(int maxDelayMillis) {
    assertDuringInitialization();//  ww w  . ja  va  2s  .co m
    this.maxDelayNanos = TimeUnit.NANOSECONDS.convert(maxDelayMillis, TimeUnit.MILLISECONDS);
}

From source file:com.vmware.identity.interop.ldap.LdapConnection.java

@Override
public void bindSaslConnection(String userName, String domainName, String userPassword) {
    this.validate();

    ILdapClientLibrary ldapClientLibrary = getLdapLibrary();

    long startedAt = System.nanoTime();
    try {//from w ww. ja v a 2 s.  c o m
        ldapClientLibrary.ldap_sasl_bind_s(this._connection, userName, domainName, userPassword);
    } finally {
        if (perfLog.isTraceEnabled()) {
            perfLog.trace(String.format("bindConnection took [%d]ms",
                    TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt)));
        }
    }
}

From source file:edu.wisc.commons.httpclient.CleanShutdownPoolingClientConnectionManager.java

@Override
public void shutdown() {
    if (shutdownComplete.get() || !this.shutdownLock.tryLock()) {
        //Already shutdown or shutdown in progress
        return;/*from w  w  w  .  j  a  v a2  s . c  o  m*/
    }

    try {
        //Create Thread to call shutdown
        final Thread shutdownThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    logger.info("PoolingClientConnectionManager shutdown started");
                    CleanShutdownPoolingClientConnectionManager.super.shutdown();
                } finally {
                    shutdownComplete.set(true);
                    logger.info("PoolingClientConnectionManager shutdown complete");
                }
            }
        });
        shutdownThread.setName("PoolingClientConnectionManager Shutdown Monitor");
        shutdownThread.setDaemon(true);

        //start shutdown thread
        shutdownThread.start();

        //track initial shutdown start time and time spent by the shutdown thread waiting or blocked
        final long shutdownStart = System.nanoTime();
        long waitStart = shutdownStart;

        //Monitor the shutdown thread
        while (!shutdownComplete.get()) {
            final long now = System.nanoTime();
            final long shutdownTime = TimeUnit.NANOSECONDS.toMillis(now - shutdownStart);

            //if time spent shutting down is greater than kill time forcibly stop the shutdown thread
            if (shutdownTime > this.shutdownThreadKillTime) {
                final String stackTrace = getStackTrace(shutdownThread);
                logger.error("Shutdown thread " + shutdownThread.getName() + " has been stopping for "
                        + shutdownTime + "ms, killing it. THIS IS BAD. \n" + stackTrace);
                shutdownThread.stop();

                //break out of the monitoring loop
                break;
            }
            //if time spent shutting down is greater than max time immediately interrupt the thread
            else if (shutdownTime > this.shutdownThreadMaxTime) {
                logger.warn("Shutdown thread " + shutdownThread.getName() + " has been stopping for "
                        + shutdownTime + "ms, interrupting immediately");
                shutdownThread.interrupt();
            }
            //otherwise check the state of the thread
            else {
                //If the thread is blocked or waiting and has been for longer than the max wait time
                //interrupt the thread. If not in blocked or waiting state update the wait-start time
                final State state = shutdownThread.getState();
                switch (state) {
                case BLOCKED:
                case TIMED_WAITING:
                case WAITING: {
                    final long waitTime = TimeUnit.NANOSECONDS.toMillis(now - waitStart);
                    if (waitTime > shutdownThreadMaxWaitTime) {
                        logger.info("Shutdown thread " + shutdownThread.getName() + " has been waiting for "
                                + waitTime + "ms, interrupting");
                        shutdownThread.interrupt();
                    } else {
                        break;
                    }
                }

                default: {
                    waitStart = now;
                    break;
                }
                }
            }

            //Sleep between state checks, don't want to overload anything
            try {
                Thread.sleep(shutdownThreadPollRate);
            } catch (InterruptedException e) {
                //ignore
            }
        }
    } finally {
        this.shutdownLock.unlock();
    }
}

From source file:com.proofpoint.http.client.ApacheHttpClient.java

public <T, E extends Exception> T execute(Request request, final ResponseHandler<T, E> responseHandler)
        throws E {
    Preconditions.checkNotNull(request, "request is null");
    Preconditions.checkNotNull(responseHandler, "responseHandler is null");

    for (HttpRequestFilter requestFilter : requestFilters) {
        request = requestFilter.filterRequest(request);
    }//from  w ww.j  ava  2  s. c  o  m

    final long requestStart = System.nanoTime();
    final StatsHttpUriRequest httpUriRequest = StatsHttpUriRequest.createGenericHttpRequest(request);
    final Request finalRequest = request;
    try {
        T value = httpClient.execute(httpUriRequest, new org.apache.http.client.ResponseHandler<T>() {
            @Override
            public T handleResponse(HttpResponse httpResponse) throws IOException {
                long responseStart = System.nanoTime();

                Response response = new MyResponse(httpResponse);
                try {
                    T value = responseHandler.handle(finalRequest, response);
                    return value;
                } catch (Exception e) {
                    throw new ExceptionFromResponseHandler(e);
                } finally {
                    Duration responseProcessingTime = Duration.nanosSince(responseStart);
                    Duration requestProcessingTime = new Duration(responseStart - requestStart,
                            TimeUnit.NANOSECONDS);

                    stats.record(finalRequest.getMethod(), response.getStatusCode(),
                            httpUriRequest.getBytesWritten(), response.getBytesRead(), requestProcessingTime,
                            responseProcessingTime);
                }
            }
        });
        return value;
    } catch (Exception e) {
        if (e instanceof ExceptionFromResponseHandler) {
            try {
                throw (E) e.getCause();
            } catch (ClassCastException classCastException) {
                // this should never happen but generics suck so be safe
                // handler will be notified of the same exception again below
            }
        } else if (e instanceof ConnectTimeoutException) {
            // apache http client eats the socket timeout exception
            SocketTimeoutException socketTimeoutException = new SocketTimeoutException(e.getMessage());
            socketTimeoutException.setStackTrace(e.getStackTrace());
            return responseHandler.handleException(request, socketTimeoutException);
        }
        return responseHandler.handleException(request, e);
    }
}

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

/**
 * Make sure the run method passes in the expected date.
 *//*w  w  w  .  j  a  v a 2  s  .  com*/
@Test
public void canRun() {
    final int days = 5;
    final int negativeDays = -1 * days;
    final int pageSize = 10;
    final int maxDeleted = 10_000;

    Mockito.when(this.cleanupProperties.getRetention()).thenReturn(days).thenReturn(negativeDays);
    Mockito.when(this.cleanupProperties.getPageSize()).thenReturn(pageSize);
    Mockito.when(this.cleanupProperties.getMaxDeletedPerTransaction()).thenReturn(maxDeleted);
    final ArgumentCaptor<Date> argument = ArgumentCaptor.forClass(Date.class);

    final long deletedCount1 = 6L;
    final long deletedCount2 = 18L;
    final long deletedCount3 = 2L;
    Mockito.when(this.jobPersistenceService.deleteBatchOfJobsCreatedBeforeDate(Mockito.any(Date.class),
            Mockito.anyInt(), Mockito.anyInt())).thenReturn(deletedCount1).thenReturn(0L)
            .thenReturn(deletedCount2).thenReturn(deletedCount3).thenReturn(0L);

    // The multiple calendar instances are to protect against running this test when the day flips
    final Calendar before = Calendar.getInstance(JobConstants.UTC);
    this.task.run();
    Assert.assertThat(this.numDeletedJobs.get(), Matchers.is(deletedCount1));
    Mockito.verify(this.deletionTimerId, Mockito.times(1)).withTags(MetricsUtils.newSuccessTagsMap());
    this.task.run();
    final Calendar after = Calendar.getInstance(JobConstants.UTC);
    Assert.assertThat(this.numDeletedJobs.get(), Matchers.is(deletedCount2 + deletedCount3));
    Mockito.verify(this.deletionTimerId, Mockito.times(2)).withTags(MetricsUtils.newSuccessTagsMap());
    Mockito.verify(this.deletionTimer, Mockito.times(2)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));

    if (before.get(Calendar.DAY_OF_YEAR) == after.get(Calendar.DAY_OF_YEAR)) {
        Mockito.verify(this.jobPersistenceService, Mockito.times(5)).deleteBatchOfJobsCreatedBeforeDate(
                argument.capture(), Mockito.eq(maxDeleted), Mockito.eq(pageSize));
        final Calendar date = Calendar.getInstance(JobConstants.UTC);
        date.set(Calendar.HOUR_OF_DAY, 0);
        date.set(Calendar.MINUTE, 0);
        date.set(Calendar.SECOND, 0);
        date.set(Calendar.MILLISECOND, 0);
        date.add(Calendar.DAY_OF_YEAR, negativeDays);
        Assert.assertThat(argument.getAllValues().get(0), Matchers.is(date.getTime()));
        Assert.assertThat(argument.getAllValues().get(1), Matchers.is(date.getTime()));
    }
}

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

/**
 * Make sure we can't load authentication if there are no authorities.
 *
 * @throws AuthenticationException On error
 * @throws InvalidTokenException   When the token is invalid
 * @throws InvalidJwtException     On invalid JWT token
 * @throws MalformedClaimException A bad claim
 *///ww  w.  j a  va 2 s  .c  om
@Test(expected = InvalidTokenException.class)
public void cantLoadAuthentication()
        throws AuthenticationException, InvalidTokenException, InvalidJwtException, MalformedClaimException {
    final JwtClaims claims = Mockito.mock(JwtClaims.class);
    final String clientId = UUID.randomUUID().toString();
    final Set<String> scopes = Sets.newHashSet();
    Mockito.when(claims.getClaimValue("client_id", String.class)).thenReturn(clientId);
    Mockito.when(claims.getClaimValue("scope", Collection.class)).thenReturn(scopes);
    Mockito.when(this.jwtConsumer.processToClaims(Mockito.anyString())).thenReturn(claims);

    this.tokenServices.loadAuthentication(UUID.randomUUID().toString());
    Mockito.verify(this.loadAuthenticationTimer, Mockito.times(1)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));
}

From source file:com.github.rozidan.springboot.logger.LoggerMsgFormatter.java

private String durationString(long nano) {
    return Duration.ofMillis(TimeUnit.NANOSECONDS.toMillis(nano)).toString();
}

From source file:co.paralleluniverse.galaxy.core.BackupImpl.java

@ManagedAttribute
public int getMaxDelay() {
    return (int) TimeUnit.MILLISECONDS.convert(maxDelayNanos, TimeUnit.NANOSECONDS);
}

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

/**
 * {@inheritDoc}// w  w w.  j  a va  2 s.c o  m
 */
@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();
    final Set<Tag> tags = Sets.newHashSet();
    try {
        log.debug("Called with src path {} and destination path {}", srcRemotePath, dstLocalPath);

        final AmazonS3URI s3Uri = getS3Uri(srcRemotePath);
        try {
            this.s3ClientFactory.getClient(s3Uri)
                    .getObject(new GetObjectRequest(s3Uri.getBucket(), s3Uri.getKey()), new File(dstLocalPath));
        } catch (final AmazonS3Exception ase) {
            log.error("Error fetching file {} from s3 due to exception {}", srcRemotePath, ase.toString());
            throw new GenieServerException("Error downloading file from s3. Filename: " + srcRemotePath, ase);
        }
        MetricsUtils.addSuccessTags(tags);
    } catch (Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.registry.timer(DOWNLOAD_TIMER_NAME, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}