Example usage for java.util.concurrent TimeUnit MICROSECONDS

List of usage examples for java.util.concurrent TimeUnit MICROSECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit MICROSECONDS.

Prototype

TimeUnit MICROSECONDS

To view the source code for java.util.concurrent TimeUnit MICROSECONDS.

Click Source Link

Document

Time unit representing one thousandth of a millisecond.

Usage

From source file:org.asoem.greyfish.utils.collect.UnrolledListAT.java

protected static <T> long measureFindFirstUnrolled(final FunctionalList<T> list,
        final Iterable<? extends Predicate<? super T>> predicates) {
    final Stopwatch stopwatch = Stopwatch.createStarted();
    for (Predicate<? super T> predicate : predicates) {
        list.findFirst(predicate);//from  w  w w.  ja v  a  2  s  .c o m
    }
    return stopwatch.elapsed(TimeUnit.MICROSECONDS);
}

From source file:test.RunTest.java

public static void writeObject(Object object, String fileName) {
    long begin = System.nanoTime();
    Hessian2Output oos = null;/*w  ww . j a  v  a  2s  . c  o  m*/
    try {
        oos = new Hessian2Output(new FileOutputStream(fileName));
        oos.setCloseStreamOnClose(true);
        oos.writeObject(object);
        oos.close();
        long end = System.nanoTime();
        logger.info("Time for Serize java object file " + fileName + "  duration micro seconds="
                + TimeUnit.MICROSECONDS.convert((end - begin), TimeUnit.NANOSECONDS));
    } catch (Exception ex) {
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException iox) {
                logger.error(ex.getMessage(), iox);
            }
        }

        logger.error(ex.getMessage(), ex);
        throw new RuntimeException(ex.getMessage(), ex);
    }

}

From source file:io.rhiot.component.gp2y1010au0f.Gp2y1010au0fConsumer.java

@Override
protected int poll() throws Exception {
    int iterations = 10;
    double sum = 0.0;

    for (int i = 0; i < iterations; i++) {
        getEndpoint().getIledPin().high();
        TimeUnit.MICROSECONDS.sleep(getEndpoint().getSamplingDelay());
        double adcValue = getEndpoint().getMcp3008GpioProvider().getValue(getEndpoint().getAnalogPin());
        getEndpoint().getIledPin().low();

        double voltage = (REF_VOLTAGE / 1023.0) * adcValue * 11;

        if (voltage > MIN_VOLTAGE) {
            sum += (voltage - MIN_VOLTAGE) * 0.2;
        }/*from w ww .ja  v  a  2  s. co m*/

        TimeUnit.MILLISECONDS.sleep(50);
    }

    double average = sum / iterations;

    if (average > 0) {
        Exchange exchange = ExchangeBuilder.anExchange(getEndpoint().getCamelContext())
                .withBody(Precision.round(average, 2)).build();
        exchange.setFromEndpoint(getEndpoint());
        getProcessor().process(exchange);
        return 1;
    }

    return 0;
}

From source file:org.wso2.andes.server.virtualhost.plugins.SlowConsumerDetectionConfigurationTest.java

/**
 * Default Testing:// w  w w  . java 2  s  . c  om
 *
 * Provide a fully complete and valid configuration specifying 'delay' and
 * 'timeunit' and ensure that it is correctly processed.
 *
 * Ensure no exceptions are thrown and that we get the same values back that
 * were put into the configuration.
 */
public void testConfigLoadingValidConfig() {
    SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();

    long DELAY = 10;
    String TIMEUNIT = TimeUnit.MICROSECONDS.toString();
    xmlconfig.addProperty("delay", String.valueOf(DELAY));
    xmlconfig.addProperty("timeunit", TIMEUNIT);

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try {
        config.setConfiguration("", composite);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    assertEquals("Delay not correctly returned.", DELAY, config.getDelay());
    assertEquals("TimeUnit not correctly returned.", TIMEUNIT, String.valueOf(config.getTimeUnit()));
}

From source file:com.otz.couchbase.client.AbstractCouchbaseClient.java

public <T extends Serializable> Observable<T> lockAndUpsert(Key<T> key, String id, T object) {
    return Observable.just(RawJsonDocument.create(key.fullKey(id), gson.toJson(object)))
            .flatMap(rawJsonDocument -> bucket.replace(rawJsonDocument)
                    .retryWhen(RetryBuilder.anyOf(CASMismatchException.class).max(10)
                            .delay(Delay.fixed(10, TimeUnit.MICROSECONDS)).build())
                    .onErrorResumeNext((Func1<Throwable, Observable<RawJsonDocument>>) throwable -> {
                        // if doc does not exist on replace, fall back to insert
                        if (throwable instanceof DocumentDoesNotExistException) {
                            return bucket.insert(rawJsonDocument);
                        }/*w  ww. j a v a  2s .  c  o m*/
                        // if other error, forward it
                        return Observable.error(throwable);
                    }))
            .flatMap(createdDocument -> Observable.just(object));
}

From source file:com.ryantenney.metrics.spring.reporter.AbstractScheduledReporterFactoryBean.java

/**
 * Parses and converts to nanoseconds a string representing
 * a duration, ie: 500ms, 30s, 5m, 1h, etc
 * @param duration a string representing a duration
 * @return the duration in nanoseconds/*  ww w  .  j  av  a2s  . c  o  m*/
 */
protected long convertDurationString(String duration) {
    final Matcher m = DURATION_STRING_PATTERN.matcher(duration);
    if (!m.matches()) {
        throw new IllegalArgumentException("Invalid duration string format");
    }

    final long sourceDuration = Long.parseLong(m.group(1));
    final String sourceUnitString = m.group(2);
    final TimeUnit sourceUnit;
    if ("ns".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.NANOSECONDS;
    } else if ("us".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MICROSECONDS;
    } else if ("ms".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MILLISECONDS;
    } else if ("s".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.SECONDS;
    } else if ("m".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MINUTES;
    } else if ("h".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.HOURS;
    } else if ("d".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.DAYS;
    } else {
        sourceUnit = TimeUnit.MILLISECONDS;
    }

    return sourceUnit.toNanos(sourceDuration);
}

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

/**
 * {@inheritDoc}// w ww  . j av  a2 s. c  om
 */
@Override
public FieldType getType() {

    if (this.sourceUnit.equals(TimeUnit.NANOSECONDS)) {

        return FieldType.NANOSECONDS_TIMESTAMP;
    }

    if (this.sourceUnit.equals(TimeUnit.MICROSECONDS)) {

        return FieldType.MICROSECONDS_TIMESTAMP;
    }

    if (this.sourceUnit.equals(TimeUnit.MILLISECONDS)) {

        return FieldType.MILLISECONDS_TIMESTAMP;
    }

    return FieldType.SECONDS_TIMESTAMP;
}

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

public static Duration microseconds(long count) {
    return new Duration(count, TimeUnit.MICROSECONDS);
}

From source file:org.apache.hadoop.hbase.ipc.TestFifoRpcScheduler.java

private ThreadPoolExecutor disableHandlers(RpcScheduler scheduler) {
    ThreadPoolExecutor rpcExecutor = null;

    try {//from  w ww  . j  av  a2s.  c  om
        Field ExecutorField = scheduler.getClass().getDeclaredField("executor");
        ExecutorField.setAccessible(true);

        scheduler.start();
        rpcExecutor = (ThreadPoolExecutor) ExecutorField.get(scheduler);

        rpcExecutor.setMaximumPoolSize(1);
        rpcExecutor.allowCoreThreadTimeOut(true);
        rpcExecutor.setCorePoolSize(0);
        rpcExecutor.setKeepAliveTime(1, TimeUnit.MICROSECONDS);

        // Wait for 2 seconds, so that idle threads will die
        Thread.sleep(2000);

    } catch (NoSuchFieldException e) {
        LOG.error("No such field exception:" + e);
    } catch (IllegalAccessException e) {
        LOG.error("Illegal access exception:" + e);
    } catch (InterruptedException e) {
        LOG.error("Interrupted exception:" + e);
    }

    return rpcExecutor;
}

From source file:org.trnltk.morphology.contextless.parser.parsing.base.BaseContextlessMorphologicParserSimpleParseSetSpeedTest.java

protected void shouldParseParseSetN(String index, boolean profilingMode) throws IOException {
    final CharSource charSource = Resources.asCharSource(
            Resources.getResource("simpleparsesets/simpleparseset" + index + ".txt"), Charset.forName("utf-8"));

    //read all in advance
    final List<Pair<String, String>> lines = charSource
            .readLines(new LineProcessor<List<Pair<String, String>>>() {
                final ImmutableList.Builder<Pair<String, String>> builder = ImmutableList.builder();

                @Override//from   www .  ja  v a 2s.c  o  m
                public boolean processLine(final String line) throws IOException {
                    if (!"#END#OF#SENTENCE#".equals(line)) {
                        final String[] split = line.split("=", 2);
                        Validate.isTrue(split.length == 2, line);
                        builder.add(Pair.of(split[0], split[1]));
                    }
                    return true;
                }

                @Override
                public List<Pair<String, String>> getResult() {
                    return builder.build();
                }
            });

    System.out.println("Number of words to parse " + lines.size());
    final Stopwatch stopwatch = Stopwatch.createUnstarted();
    if (profilingMode) {
        System.out.println("Start profiling now and then press enter!");
        new Scanner(System.in).nextLine();
    }
    stopwatch.start();
    for (Pair<String, String> line : lines) {
        final String surfaceToParse = line.getLeft();
        this.parse(surfaceToParse);
    }
    stopwatch.stop();
    System.out.println("Parsed all of them in " + stopwatch);
    System.out.println(
            "Avg time is " + stopwatch.elapsed(TimeUnit.MILLISECONDS) * 1.0 / (lines.size()) + " milliseconds");
    System.out.println(
            "Avg time is " + stopwatch.elapsed(TimeUnit.MICROSECONDS) * 1.0 / (lines.size()) + " microseconds");
    if (profilingMode) {
        System.out.println("Stop profiling now and then press enter!");
        new Scanner(System.in).nextLine();
    }
}