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.agatom.springatom.webmvc.controllers.wizard.SVWizardController.java

/**
 * <b>onStepInit</b> picks up {@link WizardProcessor} according to the {@code wizard} (corresponds to value in {@link #processorMap}) and calls
 * {@link WizardProcessor#onStepInit(String, java.util.Locale)}.
 * Returned value contains all <b>data</b> to properly sets up active step in client.
 *
 * @param wizard unique id of the {@link WizardProcessor}
 * @param step   step id (unique within wizard)
 * @param locale current locale (vital to return descriptor with valid labels etc.)
 *
 * @return {@link .WizardSubmission} the submission
 *//*from www. j a  va 2 s  . c om*/
public WizardSubmission onStepInit(final String wizard, final String step, final Locale locale)
        throws Exception {
    LOGGER.debug(String.format("onStepInit(wizard=%s,step=%s,locale=%s)", wizard, step, locale));

    final long startTime = System.nanoTime();

    WizardSubmission submission = null;
    WizardResult result;

    try {

        final WizardProcessor wizardProcessor = this.processorMap.get(wizard);
        result = wizardProcessor.onStepInit(step, locale);

    } catch (Exception exp) {
        LOGGER.debug(String.format("onStepInit(wizard=%s,step=%s) failed", wizard, step), exp);
        throw exp;
    }
    final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);

    if (result != null) {
        submission = (WizardSubmission) new WizardSubmission(result, Submission.INIT_STEP).setSize(1)
                .setSuccess(true).setTime(endTime);
    }

    LOGGER.trace(String.format("onStepInit(wizard=%s,step=%s,locale=%s) completed in %d ms", wizard, step,
            locale, endTime));

    return submission;
}

From source file:org.agatom.springatom.web.NewUserWizardProcessor.java

@Override
protected WizardResult submitWizard(NUser contextObject, final ModelMap stepData, final Locale locale)
        throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("submitWizard(contextObject=%s)", contextObject));
    }/*w  w w. j  a v a2 s  .c om*/
    final long startTime = System.nanoTime();
    final WizardResult result = new WizardResult().setWizardId(this.getWizardID());

    final NPerson person = this.getPerson(stepData);
    final Collection<SimpleGrantedAuthority> authorities = this.getAuthorities(stepData);

    try {
        contextObject = this.userService.registerNewUser(contextObject, person);
        result.setOid(this.getOID(contextObject));
    } catch (Exception exp) {
        result.addError(Throwables.getRootCause(exp));
        result.addFeedbackMessage(FeedbackMessage.newError()
                .setMessage(this.messageSource.getMessage("newUser.user.registrationFailed",
                        new Object[] { contextObject.getUsername(), exp.getMessage() }, locale)));
    }

    final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("submitWizard(contextObject=%s) took %d ms", contextObject, endTime));
    }
    result.addDebugData(WizardDebugDataKeys.SUBMISSION_TIME, endTime);
    return result;
}

From source file:org.apache.solr.client.solrj.retry.RetryingSolrServer.java

@Override
public NamedList<Object> request(final SolrRequest request) throws SolrServerException, IOException {
    int retryCount = 0;
    RetryPolicy retryPolicy = null;//from   w w w .j av a 2  s.c o m
    totalRequestCount.incrementAndGet();
    getMetrics().markMeter(ROOT_PREFIX + "requests", 1);
    Map<String, MutableLong> exceptionRootCauseCounters = new HashMap<String, MutableLong>();
    final long startTime = System.nanoTime();
    while (true) {
        final long nanosToWaitForRateLimiter = limitRequestRate(request);
        try {
            isShuttingDown.await(nanosToWaitForRateLimiter, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            ; // ignore
        }

        final long lastStartTime = System.nanoTime();
        NamedList response;
        try {
            response = solrServer.request(request);
        } catch (Exception exception) {
            long requestDuration = System.nanoTime() - lastStartTime;
            String exceptionTopLevelMsg = limitStringLength(getExceptionKey(exception));
            String exceptionRootCauseMsg = limitStringLength(getExceptionKey(getRootCause(exception)));
            String requestKey = limitStringLength(getRequestKey(request));
            handleException(request, exceptionTopLevelMsg, exceptionRootCauseMsg, requestKey, requestDuration);
            String reason = "n/a";
            boolean retry = !isShuttingDown();
            if (!retry) {
                reason = "Solrj client is shutting down";
            } else {
                retryPolicy = retryPolicyFactory.getRetryPolicy(exception, request, solrServer, retryPolicy);
                retry = retryPolicy != null;
                if (!retry) {
                    reason = "Exception is non-retryable per RetryPolicyFactory {" + retryPolicyFactory + "}";
                } else {
                    if (ENABLE_LOGGING) {
                        LOG.warn("Retryable exception received: ", exception);
                    }
                    retry = retryPolicy.allowRetry(retryCount, System.nanoTime() - startTime, sleeper);
                    if (!retry) {
                        reason = "Request must not be retried " + (retryCount > 0 ? "anymore " : "")
                                + "per RetryPolicy {" + retryPolicy + "}";
                    } else {
                        retry = !isShuttingDown(); // recheck
                        if (!retry) {
                            reason = "Solrj client is shutting down(2)";
                        }
                    }
                }
            }

            if (!retry) {
                // rethrow exception with added details to help users diagnose the situation
                long secs = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
                throw new RetriesExhaustedException("Performed " + totalRetryCount + " retries across "
                        + totalRequestCount + " client requests. Gave up because the last " + retryCount
                        + " retries across " + secs
                        + " seconds for the current request failed with this reason: '" + reason + "' and these"
                        + " root causes: ", exceptionRootCauseCounters, exception);
            }

            if (ENABLE_LOGGING) {
                LOG.info("Retrying request: {}", requestKey);
            }
            assert exception != null;
            retryCount++;
            totalRetryCount.incrementAndGet();
            incCounter(exceptionRootCauseCounters, exceptionRootCauseMsg);
            metrics.markMeter(ROOT_PREFIX + "retries", 1);
            continue; // retry request by continuing while(true) retry loop
        }

        // solr request succeeded without throwing an exception 
        long requestDuration = System.nanoTime() - lastStartTime;
        handleSuccess(request, response, retryCount, startTime, requestDuration);
        return response;
    }
}

From source file:com.google.android.apps.location.gps.gnsslogger.PlotFragment.java

/**
 *  Updates the CN0 versus Time plot data from a {@link GnssMeasurement}
 *//*  w  w  w  .ja  v a2 s  .  c  om*/
protected void updateCnoTab(GnssMeasurementsEvent event) {
    long timeInSeconds = TimeUnit.NANOSECONDS.toSeconds(event.getClock().getTimeNanos());
    if (mInitialTimeSeconds < 0) {
        mInitialTimeSeconds = timeInSeconds;
    }

    // Building the texts message in analysis text view
    List<GnssMeasurement> measurements = sortByCarrierToNoiseRatio(new ArrayList<>(event.getMeasurements()));
    SpannableStringBuilder builder = new SpannableStringBuilder();
    double currentAverage = 0;
    if (measurements.size() >= NUMBER_OF_STRONGEST_SATELLITES) {
        mAverageCn0 = (mAverageCn0 * mMeasurementCount
                + (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz()
                        + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz())
                        / NUMBER_OF_STRONGEST_SATELLITES)
                / (++mMeasurementCount);
        currentAverage = (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz()
                + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz())
                / NUMBER_OF_STRONGEST_SATELLITES;
    }
    builder.append(getString(R.string.history_average_hint, sDataFormat.format(mAverageCn0) + "\n"));
    builder.append(getString(R.string.current_average_hint, sDataFormat.format(currentAverage) + "\n"));
    for (int i = 0; i < NUMBER_OF_STRONGEST_SATELLITES && i < measurements.size(); i++) {
        int start = builder.length();
        builder.append(mDataSetManager.getConstellationPrefix(measurements.get(i).getConstellationType())
                + measurements.get(i).getSvid() + ": " + sDataFormat.format(measurements.get(i).getCn0DbHz())
                + "\n");
        int end = builder.length();
        builder.setSpan(
                new ForegroundColorSpan(mColorMap.getColor(measurements.get(i).getSvid(),
                        measurements.get(i).getConstellationType())),
                start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    builder.append(getString(R.string.satellite_number_sum_hint, measurements.size()));
    mAnalysisView.setText(builder);

    // Adding incoming data into Dataset
    mLastTimeReceivedSeconds = timeInSeconds - mInitialTimeSeconds;
    for (GnssMeasurement measurement : measurements) {
        int constellationType = measurement.getConstellationType();
        int svID = measurement.getSvid();
        if (constellationType != GnssStatus.CONSTELLATION_UNKNOWN) {
            mDataSetManager.addValue(CN0_TAB, constellationType, svID, mLastTimeReceivedSeconds,
                    measurement.getCn0DbHz());
        }
    }

    mDataSetManager.fillInDiscontinuity(CN0_TAB, mLastTimeReceivedSeconds);

    // Checks if the plot has reached the end of frame and resize
    if (mLastTimeReceivedSeconds > mCurrentRenderer.getXAxisMax()) {
        mCurrentRenderer.setXAxisMax(mLastTimeReceivedSeconds);
        mCurrentRenderer.setXAxisMin(mLastTimeReceivedSeconds - TIME_INTERVAL_SECONDS);
    }

    mChartView.invalidate();
}

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

/**
 * {@inheritDoc}/*from  www  .  j  a  v a  2  s.  c o  m*/
 */
@Override
public WizardResult onStepInit(final String step, final Locale locale) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("initializeStep(step=%s,locale=%s)", step, locale));
    }

    final long startTime = System.nanoTime();
    final WizardResult result = new WizardResult().setWizardId(this.getWizardID()).setStepId(step);

    try {
        final ModelMap modelMap = this.initializeStep(step, locale);
        if (!CollectionUtils.isEmpty(modelMap)) {
            result.addStepData(modelMap);
        } else {
            LOGGER.trace(String.format("%s does not initialized step=%s",
                    ClassUtils.getShortName(this.getClass()), step));
        }
    } catch (Exception exp) {
        LOGGER.error(String.format("initializeStep(step=%s) has failed", step), exp);
        result.addError(exp);
    }

    final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                String.format("initializeStep(step=%s,locale=%s) executed in %d ms", step, locale, endTime));
    }

    result.addDebugData(WizardDebugDataKeys.INIT_TIME, endTime);
    result.addDebugData(WizardDebugDataKeys.LOCALE, locale);
    result.addDebugData(WizardDebugDataKeys.PROCESSOR, ClassUtils.getShortName(this.getClass()));

    return result;
}

From source file:com.netflix.genie.web.jobs.workflow.impl.ApplicationTask.java

/**
 * {@inheritDoc}//from  ww  w.j a va 2s . c  om
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final Set<Tag> tags = Sets.newHashSet();
    final long start = System.nanoTime();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final String genieDir = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_PATH_VAR;
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        log.info("Starting Application Task for job {}",
                jobExecEnv.getJobRequest().getId().orElse(NO_ID_FOUND));

        for (final Application application : jobExecEnv.getApplications()) {
            final long applicationStart = System.nanoTime();
            final Set<Tag> applicationTags = Sets.newHashSet();
            applicationTags.add(Tag.of(MetricsConstants.TagKeys.APPLICATION_ID, application.getId()));
            applicationTags.add(
                    Tag.of(MetricsConstants.TagKeys.APPLICATION_NAME, application.getMetadata().getName()));

            try {
                final String applicationId = application.getId();

                // Create the directory for this application under applications in the cwd
                createEntityInstanceDirectory(genieDir, applicationId, AdminResources.APPLICATION);

                // Create the config directory for this id
                createEntityInstanceConfigDirectory(genieDir, applicationId, AdminResources.APPLICATION);

                // Create the dependencies directory for this id
                createEntityInstanceDependenciesDirectory(genieDir, applicationId, AdminResources.APPLICATION);

                // Get the setup file if specified and add it as source command in launcher script
                final Optional<String> setupFile = application.getResources().getSetupFile();
                if (setupFile.isPresent()) {
                    final String applicationSetupFile = setupFile.get();
                    if (StringUtils.isNotBlank(applicationSetupFile)) {
                        final String localPath = super.buildLocalFilePath(jobWorkingDirectory, applicationId,
                                applicationSetupFile, FileType.SETUP, AdminResources.APPLICATION);
                        this.fts.getFile(applicationSetupFile, localPath);

                        super.generateSetupFileSourceSnippet(applicationId, "Application:", localPath, writer,
                                jobWorkingDirectory);
                    }
                }

                // Iterate over and get all dependencies
                for (final String dependencyFile : application.getResources().getDependencies()) {
                    final String localPath = super.buildLocalFilePath(jobWorkingDirectory, applicationId,
                            dependencyFile, FileType.DEPENDENCIES, AdminResources.APPLICATION);
                    fts.getFile(dependencyFile, localPath);
                }

                // Iterate over and get all configuration files
                for (final String configFile : application.getResources().getConfigs()) {
                    final String localPath = super.buildLocalFilePath(jobWorkingDirectory, applicationId,
                            configFile, FileType.CONFIG, AdminResources.APPLICATION);
                    fts.getFile(configFile, localPath);
                }
                MetricsUtils.addSuccessTags(applicationTags);
            } catch (Throwable t) {
                MetricsUtils.addFailureTagsWithException(applicationTags, t);
                throw t;
            } finally {
                final long applicationFinish = System.nanoTime();
                this.getRegistry().timer(APPLICATION_SETUP_TIMER_NAME, applicationTags)
                        .record(applicationFinish - applicationStart, TimeUnit.NANOSECONDS);
            }
        }
        log.info("Finished Application Task for job {}",
                jobExecEnv.getJobRequest().getId().orElse(NO_ID_FOUND));
        MetricsUtils.addSuccessTags(tags);
    } catch (final Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.getRegistry().timer(APPLICATION_TASK_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}

From source file:appeng.client.gui.implementations.GuiCraftingCPU.java

@Override
public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) {
    String title = this.getGuiDisplayName(GuiText.CraftingStatus.getLocal());

    if (this.craftingCpu.getEstimatedTime() > 0 && !this.visual.isEmpty()) {
        final long etaInMilliseconds = TimeUnit.MILLISECONDS.convert(this.craftingCpu.getEstimatedTime(),
                TimeUnit.NANOSECONDS);
        final String etaTimeText = DurationFormatUtils.formatDuration(etaInMilliseconds,
                GuiText.ETAFormat.getLocal());
        title += " - " + etaTimeText;
    }//from  w  ww .j  av  a  2s .c o m

    this.fontRendererObj.drawString(title, TITLE_LEFT_OFFSET, TITLE_TOP_OFFSET, TEXT_COLOR);

    int x = 0;
    int y = 0;
    final int viewStart = this.getScrollBar().getCurrentScroll() * 3;
    final int viewEnd = viewStart + 3 * 6;

    String dspToolTip = "";
    final List<String> lineList = new LinkedList<String>();
    int toolPosX = 0;
    int toolPosY = 0;

    final int offY = 23;

    final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE;
    for (int z = viewStart; z < Math.min(viewEnd, this.visual.size()); z++) {
        final IAEItemStack refStack = this.visual.get(z);// repo.getReferenceItem( z );
        if (refStack != null) {
            GL11.glPushMatrix();
            GL11.glScaled(0.5, 0.5, 0.5);

            final IAEItemStack stored = this.storage.findPrecise(refStack);
            final IAEItemStack activeStack = this.active.findPrecise(refStack);
            final IAEItemStack pendingStack = this.pending.findPrecise(refStack);

            int lines = 0;

            if (stored != null && stored.getStackSize() > 0) {
                lines++;
            }
            boolean active = false;
            if (activeStack != null && activeStack.getStackSize() > 0) {
                lines++;
                active = true;
            }
            boolean scheduled = false;
            if (pendingStack != null && pendingStack.getStackSize() > 0) {
                lines++;
                scheduled = true;
            }

            if (AEConfig.instance.useColoredCraftingStatus && (active || scheduled)) {
                final int bgColor = (active ? AEColor.Green.blackVariant : AEColor.Yellow.blackVariant)
                        | BACKGROUND_ALPHA;
                final int startX = (x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET) * 2;
                final int startY = ((y * offY + ITEMSTACK_TOP_OFFSET) - 3) * 2;
                drawRect(startX, startY, startX + (SECTION_LENGTH * 2), startY + (offY * 2) - 2, bgColor);
            }

            final int negY = ((lines - 1) * 5) / 2;
            int downY = 0;

            if (stored != null && stored.getStackSize() > 0) {
                final String str = GuiText.Stored.getLocal() + ": "
                        + converter.toWideReadableForm(stored.getStackSize());
                final int w = 4 + this.fontRendererObj.getStringWidth(str);
                this.fontRendererObj.drawString(str,
                        (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19
                                - (w * 0.5)) * 2),
                        (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, TEXT_COLOR);

                if (this.tooltip == z - viewStart) {
                    lineList.add(GuiText.Stored.getLocal() + ": " + Long.toString(stored.getStackSize()));
                }

                downY += 5;
            }

            if (activeStack != null && activeStack.getStackSize() > 0) {
                final String str = GuiText.Crafting.getLocal() + ": "
                        + converter.toWideReadableForm(activeStack.getStackSize());
                final int w = 4 + this.fontRendererObj.getStringWidth(str);

                this.fontRendererObj.drawString(str,
                        (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19
                                - (w * 0.5)) * 2),
                        (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, TEXT_COLOR);

                if (this.tooltip == z - viewStart) {
                    lineList.add(
                            GuiText.Crafting.getLocal() + ": " + Long.toString(activeStack.getStackSize()));
                }

                downY += 5;
            }

            if (pendingStack != null && pendingStack.getStackSize() > 0) {
                final String str = GuiText.Scheduled.getLocal() + ": "
                        + converter.toWideReadableForm(pendingStack.getStackSize());
                final int w = 4 + this.fontRendererObj.getStringWidth(str);

                this.fontRendererObj.drawString(str,
                        (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19
                                - (w * 0.5)) * 2),
                        (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, TEXT_COLOR);

                if (this.tooltip == z - viewStart) {
                    lineList.add(
                            GuiText.Scheduled.getLocal() + ": " + Long.toString(pendingStack.getStackSize()));
                }
            }

            GL11.glPopMatrix();
            final int posX = x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19;
            final int posY = y * offY + ITEMSTACK_TOP_OFFSET;

            final ItemStack is = refStack.copy().getItemStack();

            if (this.tooltip == z - viewStart) {
                dspToolTip = Platform.getItemDisplayName(is);

                if (lineList.size() > 0) {
                    dspToolTip = dspToolTip + '\n' + Joiner.on("\n").join(lineList);
                }

                toolPosX = x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 8;
                toolPosY = y * offY + ITEMSTACK_TOP_OFFSET;
            }

            this.drawItem(posX, posY, is);

            x++;

            if (x > 2) {
                y++;
                x = 0;
            }
        }
    }

    if (this.tooltip >= 0 && dspToolTip.length() > 0) {
        this.drawTooltip(toolPosX, toolPosY + 10, 0, dspToolTip);
    }
}

From source file:com.datatorrent.contrib.hdht.HadoopFilePerformanceTest.java

private String stopTimer(Testfile fileType, String testType) throws IOException {
    timer.stop();/*from   w ww.ja va 2s .  co  m*/
    long elapsedMS = timer.elapsedTime(TimeUnit.MICROSECONDS);
    String testKey = testSize + "," + fileType.name() + "-" + testType;
    long fileSize = hdfs.getContentSummary(fileType.filepath()).getSpaceConsumed();
    testSummary.put(testKey, "" + elapsedMS + "," + fileSize);
    return String.format("%,d", timer.elapsedTime(TimeUnit.NANOSECONDS)) + " ns ( " + timer.toString(6) + " )";
}

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

public long toNanos() {
    return TimeUnit.NANOSECONDS.convert(length, timeUnit);
}

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

/**
 * Make sure can't get a file if the intput isn't a valid url.
 *
 * @throws GenieException On Error//from   w  w w.  ja  v  a2  s. co m
 * @throws IOException    On Error
 */
@Test(expected = GenieServerException.class)
public void cantGetWithInvalidUrl() throws GenieException, IOException {
    try {
        this.httpFileTransfer.getFile(UUID.randomUUID().toString(),
                this.temporaryFolder.getRoot().getCanonicalPath());
    } finally {
        Mockito.verify(this.downloadTimerId, Mockito.times(1))
                .withTags(MetricsUtils.newFailureTagsMapForException(new GenieServerException("test")));
        Mockito.verify(this.downloadTimer, Mockito.times(1)).record(Mockito.anyLong(),
                Mockito.eq(TimeUnit.NANOSECONDS));
    }
}