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.netflix.genie.web.services.impl.JobSpecificationServiceImpl.java

private Map<Cluster, String> queryForClustersAndCommands(final List<Criterion> clusterCriteria,
        final Criterion commandCriterion) throws GenieException {
    final long start = System.nanoTime();
    final Set<Tag> tags = Sets.newHashSet();
    try {/*from   ww  w .  j  a v a2s  .  c  o  m*/
        final Map<Cluster, String> clustersAndCommands = this.clusterPersistenceService
                .findClustersAndCommandsForCriteria(clusterCriteria, commandCriterion);
        MetricsUtils.addSuccessTags(tags);
        return clustersAndCommands;
    } catch (final Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.registry.timer(CLUSTER_COMMAND_QUERY_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}

From source file:io.netty.handler.timeout.IdleStateHandler.java

private void initialize(ChannelHandlerContext ctx) {
    // Avoid the case where destroy() is called before scheduling timeouts.
    // See: https://github.com/netty/netty/issues/143
    switch (state) {
    case 1:/*from ww w. j  a  v  a2 s  . c  om*/
    case 2:
        return;
    }

    state = 1;

    EventExecutor loop = ctx.executor();

    lastReadTime = lastWriteTime = System.nanoTime();
    if (readerIdleTimeNanos > 0) {
        readerIdleTimeout = loop.schedule(new ReaderIdleTimeoutTask(ctx), readerIdleTimeNanos,
                TimeUnit.NANOSECONDS);
    }
    if (writerIdleTimeNanos > 0) {
        writerIdleTimeout = loop.schedule(new WriterIdleTimeoutTask(ctx), writerIdleTimeNanos,
                TimeUnit.NANOSECONDS);
    }
    if (allIdleTimeNanos > 0) {
        allIdleTimeout = loop.schedule(new AllIdleTimeoutTask(ctx), allIdleTimeNanos, TimeUnit.NANOSECONDS);
    }
}

From source file:duty_scheduler.Scheduler.java

/**
 * Generates a String representation of the runtime of the algorithm
 * //www .j  av a  2s . com
 * @param nanos The number of nanoseconds that the algorithm took to run
 * @return A string describing how long the algorithm took to finish execution
 */
private static String runTime(long nanos) {
    long minutes = TimeUnit.NANOSECONDS.toMinutes(nanos) - (TimeUnit.NANOSECONDS.toHours(nanos) * MINS_PER_HR);
    long seconds = TimeUnit.NANOSECONDS.toSeconds(nanos)
            - (TimeUnit.NANOSECONDS.toMinutes(nanos) * SECS_PER_MINUTE);
    long millis = TimeUnit.NANOSECONDS.toMillis(nanos)
            - (TimeUnit.NANOSECONDS.toSeconds(nanos) * MILLIS_PER_SEC);
    return String.format("Time Elapsed: %d minutes, %d seconds, %d milliseconds", minutes, seconds, millis);
}

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

@ManagedAttribute
public long getVerySlowInvocationThresholdInMillis() {
    return TimeUnit.MILLISECONDS.convert(this.verySlowInvocationThresholdInNanos, TimeUnit.NANOSECONDS);
}

From source file:org.agatom.springatom.cmp.wizards.core.CreateObjectWizardProcessor.java

/**
 * {@inheritDoc}//  w w w.  ja v  a2 s  .  c o  m
 */
@Override
@SuppressWarnings("UnusedAssignment")
public WizardResult onStepSubmit(final String step, final Map<String, Object> stepData, final Locale locale)
        throws Exception {
    LOGGER.debug(String.format("onStepSubmit(step=%s, stepData=%s)", step, stepData));

    final long startTime = System.nanoTime();
    final boolean isSubmitStep = StringUtils.hasText(step);

    if (LOGGER.isDebugEnabled() && isSubmitStep) {
        LOGGER.debug(String.format("step=%s therefore it is a step submit", step));
    }

    T contextObject = this.getContextObject();
    // Create appropriate binder.
    DataBinder binder = isSubmitStep ? this.createStepBinder(contextObject, step)
            : this.createGlobalBinder(contextObject);

    final ModelMap params = new ModelMap().addAllAttributes(stepData);
    final WizardResult finalResult = this.bind(binder, step, params, locale);

    if (!finalResult.hasErrors()) {
        LOGGER.debug(String.format("Bound to context object=%s without any error", contextObject));
        try {
            if (isSubmitStep) {
                final WizardResult localResult = this.submitStep(contextObject, params, step, locale);
                if (localResult != null) {
                    finalResult.merge(localResult);
                } else if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(String.format("%s does not execute any step submission", this.getWizardID()));
                }
            } else {
                finalResult.merge(this.submitWizard(contextObject, params, locale));
            }
        } catch (Exception submitExp) {
            LOGGER.error(String.format("Submission failed for contextObject=%s", contextObject), submitExp);
            finalResult.addError(submitExp);
            finalResult
                    .addFeedbackMessage(FeedbackMessage.newError().setMessage(submitExp.getLocalizedMessage()));
        } finally {
            binder.close();
        }
    }

    final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(
                String.format("submitStep(step=%s, stepData=%s) executed in %d ms", step, stepData, endTime));
    }

    finalResult.addDebugData(WizardDebugDataKeys.TOTAL_TIME, endTime);
    finalResult.addDebugData(WizardDebugDataKeys.PROCESSOR, ClassUtils.getShortName(this.getClass()));
    finalResult.addDebugData(WizardDebugDataKeys.LOCALE, locale);

    // collect garbage
    binder = null;
    contextObject = null;
    System.gc();

    return finalResult;
}

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

/**
 * Test the getFile method for invalid s3 path.
 *
 * @throws GenieException If there is any problem
 *///from ww  w  . j a  va 2 s  .  c om
@Test(expected = GenieBadRequestException.class)
public void testGetFileMethodInvalidS3Path() throws GenieException {
    final String invalidS3Path = "filepath";
    try {
        this.s3FileTransfer.getFile(invalidS3Path, LOCAL_PATH);
    } finally {
        Mockito.verify(this.downloadTimer, Mockito.times(1)).record(Mockito.anyLong(),
                Mockito.eq(TimeUnit.NANOSECONDS));
        Mockito.verify(this.registry, Mockito.times(1))
                .timer(Mockito.eq(S3FileTransferImpl.DOWNLOAD_TIMER_NAME), this.tagsCaptor.capture());
        Assert.assertEquals(FAILURE_TAGS, this.tagsCaptor.getValue());
    }
}

From source file:co.paralleluniverse.photon.Photon.java

private static void printFinishStatistics(final Meter errors, final StripedTimeSeries<Long> sts,
        final StripedHistogram sh, final String testName) {
    final File file = new File(testName + ".txt");
    try (PrintWriter out = new PrintWriter(file)) {
        out.println("ErrorsCounter: " + errors.getCount());
        final long millisTime = new Date().getTime();
        final long nanoTime = System.nanoTime();
        sts.getRecords()//from w  w  w .  j a  va 2s  .  c om
                .forEach(rec -> out.println(df
                        .format(new Date(millisTime - TimeUnit.NANOSECONDS.toMillis(nanoTime - rec.timestamp)))
                        + " " + testName + " responseTime " + rec.value + "ms"));
        out.println("\nHistogram:");
        for (int i = 0; i <= 100; i++)
            out.println(testName + " responseTimeHistogram " + i + "% : "
                    + sh.getHistogramData().getValueAtPercentile(i));
        System.out.println("Statistics file: " + file.getAbsolutePath());
    } catch (final FileNotFoundException ex) {
        System.err.println(ex.getMessage());
    }
}

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//  w  ww  .  j  av  a  2 s. c  om
 */
@Test(expected = GenieServerException.class)
public void cantGetLastModifiedTimeIfNotURL() throws GenieException {
    try {
        this.httpFileTransfer.getLastModifiedTime(UUID.randomUUID().toString());
    } catch (final GenieServerException e) {
        Assert.assertTrue(e.getCause() instanceof MalformedURLException);
        throw e;
    } finally {
        Mockito.verify(this.metadataTimerId, Mockito.times(1))
                .withTags(MetricsUtils.newFailureTagsMapForException(new MalformedURLException("test")));
        Mockito.verify(this.metadataTimer, Mockito.times(1)).record(Mockito.anyLong(),
                Mockito.eq(TimeUnit.NANOSECONDS));
    }
}

From source file:com.netflix.genie.core.services.impl.LocalJobRunner.java

private File createJobWorkingDirectory(final String id) throws GenieException {
    final long start = System.nanoTime();
    try {/* w w  w.  j  a v  a  2s  .c  o  m*/
        final File jobDir = new File(this.baseWorkingDirPath.getFile(), id);
        if (!jobDir.mkdirs()) {
            throw new GenieServerException(
                    "Could not create job working directory directory: " + jobDir.getCanonicalPath());
        }
        log.info("Created job dir {}", jobDir);
        return jobDir;
    } catch (final IOException ioe) {
        throw new GenieServerException("Could not resolve job working directory due to exception", ioe);
    } finally {
        this.createJobDirTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}

From source file:org.apache.drill.exec.store.http.HttpGroupScan.java

@Override
public List<EndpointAffinity> getOperatorAffinity() {
    watch.reset();//www.j a  v  a 2  s . c o  m
    watch.start();
    Map<String, DrillbitEndpoint> endpointMap = new HashMap<String, DrillbitEndpoint>();
    for (DrillbitEndpoint ep : storagePlugin.getContext().getBits()) {
        endpointMap.put(ep.getAddress(), ep);
    }

    Map<DrillbitEndpoint, EndpointAffinity> affinityMap = new HashMap<DrillbitEndpoint, EndpointAffinity>();
    for (HttpWork httpWork : httpWorks) {
        DrillbitEndpoint ep = endpointMap.get(httpWork.getHostName());
        if (ep != null) {
            EndpointAffinity affinity = affinityMap.get(ep);
            if (affinity == null) {
                affinityMap.put(ep, new EndpointAffinity(ep, 1));
            } else {
                affinity.addAffinity(1);
            }
        }
    }
    logger.debug("Took {} s to get operator affinity", watch.elapsed(TimeUnit.NANOSECONDS) / 1000);
    return Lists.newArrayList(affinityMap.values());
}