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.core.jobs.workflow.impl.JobTask.java

/**
 * {@inheritDoc}//w  ww  .  ja  va  2s.  co m
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        final String jobId = jobExecEnv.getJobRequest().getId()
                .orElseThrow(() -> new GeniePreconditionException("No job id found. Unable to continue"));
        log.info("Starting Job Task for job {}", jobId);

        final Optional<String> setupFile = jobExecEnv.getJobRequest().getSetupFile();
        if (setupFile.isPresent()) {
            final String jobSetupFile = setupFile.get();
            if (StringUtils.isNotBlank(jobSetupFile)) {
                final String localPath = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER + jobSetupFile
                        .substring(jobSetupFile.lastIndexOf(JobConstants.FILE_PATH_DELIMITER) + 1);

                fts.getFile(jobSetupFile, localPath);

                writer.write("# Sourcing setup file specified in job request" + System.lineSeparator());
                writer.write(
                        JobConstants.SOURCE
                                + localPath.replace(jobWorkingDirectory,
                                        "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}")
                                + System.lineSeparator());

                // Append new line
                writer.write(System.lineSeparator());
            }
        }

        // Iterate over and get all dependencies
        for (final String dependencyFile : jobExecEnv.getJobRequest().getDependencies()) {
            if (StringUtils.isNotBlank(dependencyFile)) {
                final String localPath = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER + dependencyFile
                        .substring(dependencyFile.lastIndexOf(JobConstants.FILE_PATH_DELIMITER) + 1);

                fts.getFile(dependencyFile, localPath);
            }
        }

        // Copy down the attachments if any to the current working directory
        this.attachmentService.copy(jobId, jobExecEnv.getJobWorkingDir());
        // Delete the files from the attachment service to save space on disk
        this.attachmentService.delete(jobId);

        // Print out the current Envrionment to a env file before running the command.
        writer.write("# Dump the environment to a env.log file" + System.lineSeparator());
        writer.write("env | sort > " + "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}"
                + JobConstants.GENIE_ENV_PATH + System.lineSeparator());

        // Append new line
        writer.write(System.lineSeparator());

        writer.write("# Kick off the command in background mode and wait for it using its pid"
                + System.lineSeparator());

        writer.write(jobExecEnv.getCommand().getExecutable() + JobConstants.WHITE_SPACE
                + jobExecEnv.getJobRequest().getCommandArgs() + JobConstants.STDOUT_REDIRECT
                + JobConstants.STDOUT_LOG_FILE_NAME + JobConstants.STDERR_REDIRECT
                + JobConstants.STDERR_LOG_FILE_NAME + " &" + System.lineSeparator());

        // Wait for the above process started in background mode. Wait lets us get interrupted by kill signals.
        writer.write("wait $!" + System.lineSeparator());

        // Append new line
        writer.write(System.lineSeparator());

        // capture exit code and write to genie.done file
        writer.write("# Write the return code from the command in the done file." + System.lineSeparator());
        writer.write(JobConstants.GENIE_DONE_FILE_CONTENT_PREFIX + JobConstants.GENIE_DONE_FILE_NAME
                + System.lineSeparator());

        // Print the timestamp once its done running.
        writer.write("echo End: `date '+%Y-%m-%d %H:%M:%S'`\n");

        log.info("Finished Job Task for job {}", jobExecEnv.getJobRequest().getId());
    } finally {
        final long finish = System.nanoTime();
        this.timer.record(finish - start, TimeUnit.NANOSECONDS);
    }
}

From source file:edu.cmu.lti.oaqa.bioqa.providers.kb.TmToolConceptProvider.java

@Override
public List<Concept> getConcepts(List<JCas> jcases) throws AnalysisEngineProcessException {
    // send request
    List<String> normalizedTexts = jcases.stream().map(JCas::getDocumentText)
            .map(PubAnnotationConvertUtil::normalizeText).collect(toList());
    ListMultimap<Integer, PubAnnotation.Denotation> index2denotations = Multimaps
            .synchronizedListMultimap(ArrayListMultimap.create());
    ExecutorService es = Executors.newCachedThreadPool();
    for (String trigger : triggers) {
        es.submit(() -> {//from   w  w w  . j av  a2s  . co  m
            try {
                List<String> denotationStrings = requestConcepts(normalizedTexts, trigger);
                assert denotationStrings.size() == jcases.size();
                for (int i = 0; i < jcases.size(); i++) {
                    PubAnnotation.Denotation[] denotations = gson.fromJson(denotationStrings.get(i),
                            PubAnnotation.Denotation[].class);
                    index2denotations.putAll(i, Arrays.asList(denotations));
                }
            } catch (Exception e) {
                throw TmToolConceptProviderException.unknownException(trigger, e);
            }
        });
    }
    es.shutdown();
    try {
        boolean status = es.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        if (!status) {
            throw new AnalysisEngineProcessException();
        }
    } catch (InterruptedException e) {
        throw new AnalysisEngineProcessException(e);
    }
    // convert denotation strings
    List<Concept> concepts = new ArrayList<>();
    for (int i = 0; i < jcases.size(); i++) {
        JCas jcas = jcases.get(i);
        List<PubAnnotation.Denotation> denotations = index2denotations.get(i);
        try {
            concepts.addAll(PubAnnotationConvertUtil.convertDenotationsToConcepts(jcas, denotations));
        } catch (StringIndexOutOfBoundsException e) {
            throw TmToolConceptProviderException.offsetOutOfBounds(jcas.getDocumentText(), denotations, e);
        }
    }
    return concepts;
}

From source file:org.apache.hadoop.hbase.client.AsyncSingleRequestRpcRetryingCaller.java

private void call(HRegionLocation loc) {
    ClientService.Interface stub;//from w w w . ja v  a 2 s.c om
    try {
        stub = conn.getRegionServerStub(loc.getServerName());
    } catch (IOException e) {
        onError(e,
                () -> "Get async stub to " + loc.getServerName() + " for '" + Bytes.toStringBinary(row)
                        + "' in " + loc.getRegionInfo().getEncodedName() + " of " + tableName
                        + " failed, tries = " + tries + ", maxAttempts = " + maxAttempts + ", timeout = "
                        + TimeUnit.NANOSECONDS.toMillis(operationTimeoutNs) + " ms, time elapsed = "
                        + elapsedMs() + " ms",
                err -> conn.getLocator().updateCachedLocations(tableName, loc.getRegionInfo().getRegionName(),
                        row, err, loc.getServerName()));
        return;
    }
    resetController();
    callable.call(controller, loc, stub).whenComplete((result, error) -> {
        if (error != null) {
            onError(error,
                    () -> "Call to " + loc.getServerName() + " for '" + Bytes.toStringBinary(row) + "' in "
                            + loc.getRegionInfo().getEncodedName() + " of " + tableName + " failed, tries = "
                            + tries + ", maxAttempts = " + maxAttempts + ", timeout = "
                            + TimeUnit.NANOSECONDS.toMillis(operationTimeoutNs) + " ms, time elapsed = "
                            + elapsedMs() + " ms",
                    err -> conn.getLocator().updateCachedLocations(tableName,
                            loc.getRegionInfo().getRegionName(), row, err, loc.getServerName()));
            return;
        }
        future.complete(result);
    });
}

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

/**
 * {@inheritDoc}/*  w  w w  .j a  v  a2s  .  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();
    final Set<Tag> tags = Sets.newHashSet();
    try {
        log.debug("Called with src path {} and destination path {}", srcLocalPath, dstRemotePath);

        final AmazonS3URI s3Uri = getS3Uri(dstRemotePath);
        try {
            this.s3ClientFactory.getClient(s3Uri).putObject(s3Uri.getBucket(), s3Uri.getKey(),
                    new File(srcLocalPath));
        } catch (final AmazonS3Exception ase) {
            log.error("Error posting file {} to s3 due to exception {}", dstRemotePath, ase.toString());
            throw new GenieServerException("Error uploading file to s3. Filename: " + dstRemotePath, ase);
        }
        MetricsUtils.addSuccessTags(tags);
    } catch (Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.registry.timer(UPLOAD_TIMER_NAME, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}

From source file:io.horizondb.model.core.fields.TimestampField.java

/**
 * Returns the unit of time for the specified symbol.
 * /*from  w w w.jav a 2  s  .c om*/
 * @param timeUnit the time unit
 * @return the unit of time for the specified symbol
 */
private TimeUnit getTimeUnit(String symbol) {

    switch (symbol) {

    case "":
        return this.sourceUnit;
    case "ns":
        return TimeUnit.NANOSECONDS;
    case "s":
        return TimeUnit.MICROSECONDS;
    case "ms":
        return TimeUnit.MILLISECONDS;
    case "s":
        return TimeUnit.SECONDS;
    default:
        throw new IllegalStateException("Unknown time unit: " + symbol);
    }
}

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

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

From source file:org.apache.hadoop.hive.ql.exec.tez.TezSessionState.java

public boolean isOpen() {
    if (session != null)
        return true;
    if (sessionFuture == null)
        return false;
    try {/* w w  w .ja v  a 2  s .c om*/
        session = sessionFuture.get(0, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    } catch (TimeoutException | CancellationException e) {
        return false;
    }
    return true;
}

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

/**
 * Make sure we can't load authentication if an exception is thrown.
 *
 * @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  o m*/
@Test
public void cantProcessClaims()
        throws AuthenticationException, InvalidTokenException, InvalidJwtException, MalformedClaimException {
    final JwtClaims claims = Mockito.mock(JwtClaims.class);
    Mockito.when(claims.getClaimValue("client_id", String.class))
            .thenThrow(new MalformedClaimException("bad claim"));
    Mockito.when(this.jwtConsumer.processToClaims(Mockito.anyString()))
            .thenThrow(new InvalidJwtException("bad jwt")).thenReturn(claims);

    try {
        this.tokenServices.loadAuthentication(UUID.randomUUID().toString());
        Assert.fail();
    } catch (final InvalidTokenException e) {
        Mockito.verify(this.jwtConsumer, Mockito.times(1)).processToClaims(Mockito.anyString());
    }

    try {
        this.tokenServices.loadAuthentication(UUID.randomUUID().toString());
        Assert.fail();
    } catch (final InvalidTokenException e) {
        Mockito.verify(this.jwtConsumer, Mockito.times(2)).processToClaims(Mockito.anyString());
    }

    Mockito.verify(this.loadAuthenticationTimer, Mockito.times(2)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));
}

From source file:com.tinspx.util.concurrent.DelayedSemaphoreTest.java

/**
 * Test of create method, of class DelayedSemaphore.
 *//*from ww w. jav a 2s.com*/
@Test
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public void testInit() throws InterruptedException {
    new DelayedSemaphore(1, 0, null);
    DelayedSemaphore.create(1, 0);
    DelayedSemaphore.create(1, 1);

    DelayedSemaphore ls = DelayedSemaphore.create(5, 50000000);
    assertEquals(5, ls.permits());
    assertEquals(5, ls.availablePermits());
    assertEquals(50000000, ls.delay());
    assertSame(Ticker.systemTicker(), ls.ticker());
    ls.acquire(); //4
    Thread.sleep(10);
    assertEquals(5, ls.permits());
    assertEquals(4, ls.availablePermits());
    ls.acquire();//3
    ls.acquire();//2
    ls.release();//3
    assertEquals(2, ls.availablePermits());
    Thread.sleep(51);
    assertEquals(3, ls.availablePermits());
    assertEquals(5, ls.permits());

    ls.release(); //4
    ls.release();//5
    try {
        ls.release();
        fail();
    } catch (IllegalStateException ex) {
    }

    assertTrue(ls.tryAcquire(-1, TimeUnit.DAYS));
    assertTrue(ls.tryAcquire(1, -1, TimeUnit.DAYS));
    Thread.sleep(51);
    assertTrue(ls.tryAcquire(2, -1, TimeUnit.DAYS));
    assertEquals(1, ls.availablePermits(0));
    try {
        ls.release(5);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    ls.release(4);
    assertEquals(5, ls.availablePermits(0));
    assertEquals(0, ls.availablePermits(TimeUnit.HOURS.toNanos(1)));

    //acquire invalid args
    try {
        ls.acquire(-1L);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(0);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(-1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(0, 10);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(-1, 10);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(1, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(2, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }

    //tryAcquire no timeout, invalid args
    try {
        ls.tryAcquire(-1L);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(-1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0, 10);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(-1, 10);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(1, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(2, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }

    //tryAcquire with timeout, invalid arguments
    try {
        ls.tryAcquire(-1L, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(-1, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0, 10, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(-1, 10, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(1, -1, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(2, -1, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0L, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }
    try {
        ls.tryAcquire(1, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }
    try {
        ls.tryAcquire(2, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }
    try {
        ls.tryAcquire(1, 0, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }
    try {
        ls.tryAcquire(2, 0, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }

    DelayedSemaphore.create(1, 0);
    try {
        DelayedSemaphore.create(0, 1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        DelayedSemaphore.create(1, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        DelayedSemaphore.create(1, 0, null);
        fail();
    } catch (NullPointerException ex) {
    }
}

From source file:fr.xebia.audit.AuditAspect.java

protected String buildMessage(String template, Object invokedObject, Object[] args, Object returned,
        Throwable throwned, long durationInNanos) {
    try {//from   w w w.j  a  va  2s . c  om
        Expression expression = expressionCache.get(template);
        if (expression == null) {
            expression = expressionParser.parseExpression(template, parserContext);
            expressionCache.put(template, expression);
        }

        String evaluatedMessage = expression.getValue(new RootObject(invokedObject, args, returned, throwned),
                String.class);

        StringBuilder msg = new StringBuilder();

        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) dateFormatPrototype.clone();
        msg.append(simpleDateFormat.format(new Date()));

        msg.append(" ").append(evaluatedMessage);

        if (throwned != null) {
            msg.append(" threw '");
            appendThrowableCauses(throwned, ", ", msg);
            msg.append("'");
        }
        msg.append(" by ");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            msg.append("anonymous");
        } else {
            msg.append(authentication.getName());
            if (authentication.getDetails() instanceof WebAuthenticationDetails) {
                WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
                msg.append(" coming from " + details.getRemoteAddress());
            }
        }
        msg.append(" in ").append(TimeUnit.MILLISECONDS.convert(durationInNanos, TimeUnit.NANOSECONDS))
                .append(" ms");
        return msg.toString();
    } catch (RuntimeException e) {
        StringBuilder msg = new StringBuilder("Exception evaluating template '" + template + "': ");
        appendThrowableCauses(e, ", ", msg);
        return msg.toString();
    }
}