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:rmblworx.tools.timey.SimpleTimerTest.java

/**
 * Test method for {@link SimpleTimer#stopStopwatch()}.
 */// w  w  w . jav a2s .  co  m
@Test
public final void testStopStopwatch() {
    this.timer.startStopwatch(1, TimeUnit.NANOSECONDS);
    assertTrue(this.timer.stopStopwatch());
}

From source file:com.rumblefish.friendlymusic.api.WebRequest.java

public static String webRequest(URLRequest request) {
    HttpPost httpPost = null;// ww  w  .  j  a v a 2  s . c o  m
    HttpGet httpGet = null;
    if (request.m_nameValuePairs != null) {
        httpPost = new HttpPost(request.m_serverURL);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(request.m_nameValuePairs));
        } catch (Exception e) {
            return null;
        }
    } else {
        httpGet = new HttpGet(request.m_serverURL);
        Log.v(LOGTAG, request.m_serverURL);
    }

    HttpClient client = getNewHttpClient(request.m_timelimit);

    StringBuilder builder = new StringBuilder();

    try {
        HttpResponse response;
        if (request.m_nameValuePairs != null)
            response = client.execute(httpPost);
        else
            response = client.execute(httpGet);

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            try {
                content.close();
            } catch (IOException e) {

            }
        } else {
            Log.e("WebRequest", "Failed to download file");
            return null;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().closeExpiredConnections();
        client.getConnectionManager().closeIdleConnections(0, TimeUnit.NANOSECONDS);
    }

    String resultString = builder.toString();
    try {
        if (resultString == null || resultString.length() == 0) {
            return null;
        }
        return resultString;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.apache.hadoop.hive.common.type.HiveIntervalDayTime.java

public void set(int days, int hours, int minutes, int seconds, int nanos) {
    long totalSeconds = seconds;
    totalSeconds += TimeUnit.DAYS.toSeconds(days);
    totalSeconds += TimeUnit.HOURS.toSeconds(hours);
    totalSeconds += TimeUnit.MINUTES.toSeconds(minutes);
    totalSeconds += TimeUnit.NANOSECONDS.toSeconds(nanos);
    nanos = nanos % IntervalDayTimeUtils.NANOS_PER_SEC;

    this.totalSeconds = totalSeconds;
    this.nanos = nanos;

    normalizeSecondsAndNanos();/*from  ww w  .ja va2  s  .  c  o m*/
}

From source file:com.hpcloud.util.Duration.java

public static Duration nanoseconds(long count) {
    return new Duration(count, TimeUnit.NANOSECONDS);
}

From source file:io.cloudslang.worker.management.services.WorkerManager.java

@PostConstruct
private void init() {
    logger.info("Initialize worker with UUID: " + workerUuid);
    System.setProperty("worker.uuid", workerUuid); //do not remove!!!
    inBuffer = new LinkedBlockingQueue<>();

    executorService = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, Long.MAX_VALUE,
            TimeUnit.NANOSECONDS, inBuffer,
            new WorkerThreadFactory((++threadPoolVersion) + "_WorkerExecutionThread"));

    mapOfRunningTasks = new ConcurrentHashMap<>(numberOfThreads);
}

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

/**
 * Load the credentials for the specified access token.
 *
 * @param accessToken The access token value.
 * @return The authentication for the access token.
 * @throws AuthenticationException If the access token is expired
 * @throws InvalidTokenException   if the token isn't valid
 *//*ww w  .j  a  v a  2s .  c om*/
@Override
public OAuth2Authentication loadAuthentication(final String accessToken)
        throws AuthenticationException, InvalidTokenException {
    final long start = System.nanoTime();

    try {
        final JwtClaims claims = this.jwtConsumer.processToClaims(accessToken);
        log.debug("Ping Federate JWT Claims: {}", claims);
        return new OAuth2Authentication(this.getOAuth2Request(claims), null);
    } catch (final InvalidJwtException | MalformedClaimException e) {
        throw new InvalidTokenException(e.getMessage(), e);
    } finally {
        this.loadAuthenticationTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}

From source file:com.arpnetworking.metrics.generator.util.TestFileGenerator.java

/**
 * Generates the test file./*  w  w  w .j av a 2 s.c  o m*/
 */
public void generate() {
    try {
        Files.deleteIfExists(_fileName);
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }

    final long totalSampleCount = ((long) _uowCount) * _namesCount * _samplesCount;
    LOGGER.info().setEvent("GeneratingFile").setMessage("Starting file generation")
            .addData("file", _fileName.toAbsolutePath()).addData("expectedSamples", totalSampleCount).log();

    final Duration duration = new Duration(_startTime, _endTime);

    final List<MetricGenerator> metricGenerators = Lists.newArrayList();
    for (int x = 0; x < _namesCount; ++x) {
        final GaussianMetricGenerator gaussian = new GaussianMetricGenerator(50d, 8d,
                new SingleNameGenerator(_random));
        final ConstantCountMetricGenerator sampleGenerator = new ConstantCountMetricGenerator(_samplesCount,
                gaussian);
        metricGenerators.add(sampleGenerator);
    }
    final UnitOfWorkGenerator uowGenerator = new UnitOfWorkGenerator(metricGenerators);

    final List<UnitOfWorkSchedule> schedules = Lists.newArrayList();
    final long durationInNanos = TimeUnit.NANOSECONDS.convert(duration.getMillis(), TimeUnit.MILLISECONDS);
    final long periodInNanos = durationInNanos / _uowCount;
    schedules.add(new UnitOfWorkSchedule(uowGenerator, new ConstantTimeScheduler(periodInNanos)));

    final MetricGenerator canary = new ConstantMetricGenerator(5, new SpecifiedName(CANARY));

    // Special canary unit of work schedulers
    // Each UOW generator is guaranteed to be executed once
    final UnitOfWorkGenerator canaryUOW = new UnitOfWorkGenerator(Collections.singletonList(canary));
    schedules
            .add(new UnitOfWorkSchedule(canaryUOW, new ConstantTimeScheduler(durationInNanos + periodInNanos)));

    final IntervalExecutor executor = new IntervalExecutor(_startTime, _endTime, schedules, _fileName,
            _clusterName, _serviceName);
    executor.execute();
    try {
        final BasicFileAttributes attributes = Files.readAttributes(_fileName, BasicFileAttributes.class);
        LOGGER.info().setEvent("GenerationComplete").setMessage("Generation completed successfully")
                .addData("size", attributes.size()).log();
    } catch (final IOException e) {
        LOGGER.warn().setEvent("GenerationComplete")
                .setMessage("Generation completed successfully but unable to read attributes of generated file")
                .setThrowable(e).log();
    }
}

From source file:com.btobits.automator.fix.ant.task.FixDisconnectExpect.java

public boolean isDisconnectHappen() {
    try {//  w w  w.ja v  a 2s  .c  o  m
        final long sleepTime = TimeUnit.NANOSECONDS.convert(timeout.getDuration(), timeout.getUnit())
                - (System.nanoTime() - startTime);
        log("Session [" + getSessionID() + "] disconnect waiting for period: "
                + TimeUnit.MILLISECONDS.convert(sleepTime, TimeUnit.NANOSECONDS) + " ms");
        return waitDoneSignal.await(sleepTime, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        return false;
    } finally {
        conn.removeConnectionListener(this);
    }
}

From source file:com.fusesource.forge.jmstest.executor.TerminatingThreadPoolExecutor.java

private void startChecker() {
    scheduledChecker = new ScheduledThreadPoolExecutor(1);
    scheduledChecker.scheduleAtFixedRate(new Runnable() {

        public void run() {
            log().debug("Checking Terminate condition for " + getName());
            long currentTime = System.currentTimeMillis();
            if (getActiveCount() == 0) {
                if (currentTime - lastSubmit.get() >= getKeepAliveTime(TimeUnit.MILLISECONDS)) {
                    log().debug("Shutting down...");
                    shutdown();//  w  w  w. j ava 2 s .co m
                }
            }
        }
    }, getKeepAliveTime(TimeUnit.NANOSECONDS), getKeepAliveTime(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);

}

From source file:org.agatom.springatom.cmp.wizards.validation.ValidatorsRepositoryImpl.java

@PostConstruct
private void loadValidators() {
    final long startTime = System.nanoTime();
    final String[] beanNames = this.beanFactory.getBeanNamesForAnnotation(WizardValidator.class);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(String.format("Located following %s=%s", ClassUtils.getShortName(WizardValidator.class),
                Arrays.toString(beanNames)));
    }//from  w w w .j  a va2 s  . c om
    this.validatorsMap = Maps.newHashMap();
    for (final String beanName : beanNames) {
        this.validatorsMap.put(beanName, this.beanFactory.getBean(beanName));
    }
    LOGGER.trace(String.format("Located %d WizardValidators in %d ms", this.validatorsMap.size(),
            TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)));
}