Java Code Examples for java.util.concurrent.TimeUnit.MICROSECONDS

The following are Jave code examples for showing how to use MICROSECONDS of the java.util.concurrent.TimeUnit class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: cas-5.1.0   File: DateTimeUtils.java   Source Code and License Vote up 6 votes
/**
 * To time unit time unit.
 *
 * @param tu the tu
 * @return the time unit
 */
public static TimeUnit toTimeUnit(final ChronoUnit tu) {
    if (tu == null) {
        return null;
    }
    switch (tu) {
        case DAYS:
            return TimeUnit.DAYS;
        case HOURS:
            return TimeUnit.HOURS;
        case MINUTES:
            return TimeUnit.MINUTES;
        case SECONDS:
            return TimeUnit.SECONDS;
        case MICROS:
            return TimeUnit.MICROSECONDS;
        case MILLIS:
            return TimeUnit.MILLISECONDS;
        case NANOS:
            return TimeUnit.NANOSECONDS;
        default:
            throw new UnsupportedOperationException("Temporal unit is not supported");
    }
}
 
Example 2
Project: neoscada   File: ModbusMaster.java   Source Code and License Vote up 6 votes
@Override
protected void configureConnector ( final NioSocketConnector connector )
{
    logger.debug ( "Configuring connector: {}", connector );

    switch ( this.protocolType )
    {
        case TYPE_TCP:
            connector.getFilterChain ().addLast ( "modbusPdu", new ProtocolCodecFilter ( new ModbusTcpEncoder (), new ModbusTcpDecoder () ) );
            connector.getFilterChain ().addLast ( "modbus", new ModbusMasterProtocolFilter () );
            break;
        case TYPE_RTU:
            // convert milliseconds to microseconds to allow more accurate timing
            final ModbusRtuDecoder rtuDecoder = new ModbusRtuDecoder ( getExecutor (), Double.valueOf ( this.interFrameDelay * 1000 ).longValue (), TimeUnit.MICROSECONDS );
            connector.getFilterChain ().addLast ( "modbusPdu", new ModbusRtuProtocolCodecFilter ( new ModbusRtuEncoder (), rtuDecoder ) );
            connector.getFilterChain ().addLast ( "modbus", new ModbusMasterProtocolFilter () );
            break;
        default:
            throw new IllegalArgumentException ( String.format ( "'%s' is not an allowed modbus device type", this.protocolType ) );
    }

    if ( Boolean.getBoolean ( "org.eclipse.scada.da.server.osgi.modbus.trace" ) )
    {
        connector.getFilterChain ().addFirst ( "logger", new LoggingFilter ( ModbusMaster.class.getName () + ".protocol" ) );
    }
}
 
Example 3
Project: ditb   File: ProtobufUtil.java   Source Code and License Vote up 6 votes
/**
 * Convert a protocol buffer TimeUnit to a client TimeUnit
 * @param proto
 * @return the converted client TimeUnit
 */
public static TimeUnit toTimeUnit(final HBaseProtos.TimeUnit proto) {
  switch (proto) {
  case NANOSECONDS:
    return TimeUnit.NANOSECONDS;
  case MICROSECONDS:
    return TimeUnit.MICROSECONDS;
  case MILLISECONDS:
    return TimeUnit.MILLISECONDS;
  case SECONDS:
    return TimeUnit.SECONDS;
  case MINUTES:
    return TimeUnit.MINUTES;
  case HOURS:
    return TimeUnit.HOURS;
  case DAYS:
    return TimeUnit.DAYS;
  default:
    throw new RuntimeException("Invalid TimeUnit " + proto);
  }
}
 
Example 4
Project: ditb   File: HBaseTestingUtility.java   Source Code and License Vote up 6 votes
/**
 * Tool to get the reference to the region server object that holds the
 * region of the specified user table.
 * It first searches for the meta rows that contain the region of the
 * specified table, then gets the index of that RS, and finally retrieves
 * the RS's reference.
 * @param tableName user table to lookup in hbase:meta
 * @return region server that holds it, null if the row doesn't exist
 * @throws IOException
 * @throws InterruptedException
 */
public HRegionServer getRSForFirstRegionInTable(TableName tableName)
    throws IOException, InterruptedException {
  List<byte[]> metaRows = getMetaTableRows(tableName);
  if (metaRows == null || metaRows.isEmpty()) {
    return null;
  }
  LOG.debug("Found " + metaRows.size() + " rows for table " +
    tableName);
  byte [] firstrow = metaRows.get(0);
  LOG.debug("FirstRow=" + Bytes.toString(firstrow));
  long pause = getConfiguration().getLong(HConstants.HBASE_CLIENT_PAUSE,
    HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
  int numRetries = getConfiguration().getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
    HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
  RetryCounter retrier = new RetryCounter(numRetries+1, (int)pause, TimeUnit.MICROSECONDS);
  while(retrier.shouldRetry()) {
    int index = getMiniHBaseCluster().getServerWith(firstrow);
    if (index != -1) {
      return getMiniHBaseCluster().getRegionServerThreads().get(index).getRegionServer();
    }
    // Came back -1.  Region may not be online yet.  Sleep a while.
    retrier.sleepUntilNextRetry();
  }
  return null;
}
 
Example 5
Project: sstable-adaptor   File: CassandraMetricsRegistry.java   Source Code and License Vote up 5 votes
public void registerMBean(Metric metric, ObjectName name)
{
    AbstractBean mbean;

    if (metric instanceof Gauge)
    {
        mbean = new JmxGauge((Gauge<?>) metric, name);
    } else if (metric instanceof Counter)
    {
        mbean = new JmxCounter((Counter) metric, name);
    } else if (metric instanceof Histogram)
    {
        mbean = new JmxHistogram((Histogram) metric, name);
    } else if (metric instanceof Meter)
    {
        mbean = new JmxMeter((Meter) metric, name, TimeUnit.SECONDS);
    } else if (metric instanceof Timer)
    {
        mbean = new JmxTimer((Timer) metric, name, TimeUnit.SECONDS, TimeUnit.MICROSECONDS);
    } else
    {
        throw new IllegalArgumentException("Unknown metric type: " + metric.getClass());
    }

    try
    {
        mBeanServer.registerMBean(mbean, name);
    } catch (Exception ignored) {}
}
 
Example 6
Project: human-mobility-modeling-utilities   File: LocationReport.java   Source Code and License Vote up 5 votes
/**
 * This method calculates location inter-report times.
 * @param traces location traces belong to a person
 * @param unit time unit
 * @return inter-report times
 * @throws InsufficientLocationTraceException
 * @throws TimeUnitNotSupportedException 
 */
public long[] calculateLocationReport(List<LocationTrace> traces, 
		TimeUnit unit) throws InsufficientLocationTraceException, TimeUnitNotSupportedException {

	if (traces == null || traces.size() < minimumNumberOfTraces) {
		throw new InsufficientLocationTraceException("LocationTrace list "
				+ "need to have at least " + minimumNumberOfTraces
				+ " elements.");
	}

	if (unit == TimeUnit.NANOSECONDS || unit == TimeUnit.MICROSECONDS
			|| unit == TimeUnit.MILLISECONDS) {
		throw new TimeUnitNotSupportedException(
				unit + " is not supported. Please pass seconds or above as time unit.");
	}
	
	long[] locationReportTimes = new long[ traces.size() - 1];
	
	DateTime date1 = traces.get(0).getUTCTime();
	DateTime date2;
	
	for (int i=1; i < traces.size(); i++){
		date2 = traces.get(i).getUTCTime();
		
		locationReportTimes[i - 1] = calculateDuration(date1, date2, unit);
		
		date1 = date2;
	}
	
	return locationReportTimes;
}
 
Example 7
Project: elasticsearch_my   File: TimeValue.java   Source Code and License Vote up 5 votes
public static TimeValue parseTimeValue(String sValue, TimeValue defaultValue, String settingName) {
    settingName = Objects.requireNonNull(settingName);
    if (sValue == null) {
        return defaultValue;
    }
    final String normalized = sValue.toLowerCase(Locale.ROOT).trim();
    if (normalized.endsWith("nanos")) {
        return new TimeValue(parse(sValue, normalized, 5), TimeUnit.NANOSECONDS);
    } else if (normalized.endsWith("micros")) {
        return new TimeValue(parse(sValue, normalized, 6), TimeUnit.MICROSECONDS);
    } else if (normalized.endsWith("ms")) {
        return new TimeValue(parse(sValue, normalized, 2), TimeUnit.MILLISECONDS);
    } else if (normalized.endsWith("s")) {
        return new TimeValue(parse(sValue, normalized, 1), TimeUnit.SECONDS);
    } else if (sValue.endsWith("m")) {
        // parsing minutes should be case sensitive as `M` is generally
        // accepted to mean months not minutes. This is the only case where
        // the upper and lower case forms indicate different time units
        return new TimeValue(parse(sValue, normalized, 1), TimeUnit.MINUTES);
    } else if (normalized.endsWith("h")) {
        return new TimeValue(parse(sValue, normalized, 1), TimeUnit.HOURS);
    } else if (normalized.endsWith("d")) {
        return new TimeValue(parse(sValue, normalized, 1), TimeUnit.DAYS);
    } else if (normalized.matches("-0*1")) {
        return TimeValue.MINUS_ONE;
    } else if (normalized.matches("0+")) {
        return TimeValue.ZERO;
    } else {
        // Missing units:
        throw new ElasticsearchParseException(
            "failed to parse setting [{}] with value [{}] as a time value: unit is missing or unrecognized",
            settingName,
            sValue);
    }
}
 
Example 8
Project: monarch   File: InternalDataSerializer.java   Source Code and License Vote up 5 votes
/**
 * Reads a <code>TimeUnit</code> from a <code>DataInput</code>.
 *
 * @throws IOException A problem occurs while writing to <code>out</code>
 */
public static TimeUnit readTimeUnit(DataInput in) throws IOException {

  InternalDataSerializer.checkIn(in);

  byte type = in.readByte();

  TimeUnit unit;
  switch (type) {
    case TIME_UNIT_NANOSECONDS:
      unit = TimeUnit.NANOSECONDS;
      break;
    case TIME_UNIT_MICROSECONDS:
      unit = TimeUnit.MICROSECONDS;
      break;
    case TIME_UNIT_MILLISECONDS:
      unit = TimeUnit.MILLISECONDS;
      break;
    case TIME_UNIT_SECONDS:
      unit = TimeUnit.SECONDS;
      break;
    default:
      throw new IOException(LocalizedStrings.DataSerializer_UNKNOWN_TIMEUNIT_TYPE_0
          .toLocalizedString(Byte.valueOf(type)));
  }

  if (logger.isTraceEnabled(LogMarker.SERIALIZER)) {
    logger.trace(LogMarker.SERIALIZER, "Read TimeUnit: {}", unit);
  }

  return unit;
}
 
Example 9
Project: iextrading4j-hist   File: LotsOfFieldsBenchmark.java   Source Code and License Vote up 4 votes
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public IEXMessage lotsOfFieldsBenchmark(final LotsOfFieldsBenchmark.BenchmarkState benchmarkState) {
    return createIEXMessage(benchmarkState.packet);
}
 
Example 10
Project: iextrading4j-hist   File: BigSegmentBenchmark.java   Source Code and License Vote up 4 votes
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public IEXSegment bigSegmentBenchmark(final BenchmarkState benchmarkState) {
    return createIEXSegment(benchmarkState.packet);
}
 
Example 11
Project: iextrading4j-hist   File: LotsOfEnumsBenchmark.java   Source Code and License Vote up 4 votes
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public IEXMessage lotsOfEnumsBenchmark(final LotsOfEnumsBenchmark.BenchmarkState benchmarkState) {
    return createIEXMessage(benchmarkState.packet);
}
 
Example 12
Project: mumu-benchmark   File: JMHSample_02_BenchmarkModes.java   Source Code and License Vote up 4 votes
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureAvgTime() throws InterruptedException {
    TimeUnit.MILLISECONDS.sleep(100);
}
 
Example 13
Project: mumu-benchmark   File: JMHSample_02_BenchmarkModes.java   Source Code and License Vote up 4 votes
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureSamples() throws InterruptedException {
    TimeUnit.MILLISECONDS.sleep(100);
}
 
Example 14
Project: mumu-benchmark   File: JMHSample_02_BenchmarkModes.java   Source Code and License Vote up 4 votes
@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureSingleShot() throws InterruptedException {
    TimeUnit.MILLISECONDS.sleep(100);
}
 
Example 15
Project: mumu-benchmark   File: JMHSample_02_BenchmarkModes.java   Source Code and License Vote up 4 votes
@Benchmark
@BenchmarkMode({Mode.Throughput, Mode.AverageTime, Mode.SampleTime, Mode.SingleShotTime})
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureMultiple() throws InterruptedException {
    TimeUnit.MILLISECONDS.sleep(100);
}
 
Example 16
Project: mumu-benchmark   File: JMHSample_02_BenchmarkModes.java   Source Code and License Vote up 4 votes
@Benchmark
@BenchmarkMode(Mode.All)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void measureAll() throws InterruptedException {
    TimeUnit.MILLISECONDS.sleep(100);
}
 
Example 17
Project: grpc-proxy   File: StatsTracerFactory.java   Source Code and License Vote up 4 votes
private Recorder newRecorder() {
  return new Recorder(MIN_DURATION, MAX_DURATION, GOAL_DURATION, TimeUnit.MICROSECONDS);
}
 
Example 18
Project: grpc-proxy   File: HelloWorldClient.java   Source Code and License Vote up 4 votes
@Override
public void run() {
  try {
    final TlsContext tls = new TlsContext(trustedCertsPath, certPath, keyPath);
    final HelloWorldClient client = new HelloWorldClient(hostname, port, tls);
    try {
      final Recorder recorder =
          new Recorder(
              500,
              TimeUnit.MINUTES.toMicros(1),
              TimeUnit.MILLISECONDS.toMicros(10),
              TimeUnit.MICROSECONDS);
      LOGGER.info("Initial request: {}", client.greet(requests));
      LOGGER.info("Sending {} requests from {} threads", requests, threads);

      final ExecutorService threadPool = Executors.newFixedThreadPool(threads);
      final Instant start = Instant.now();
      for (int i = 0; i < threads; i++) {
        threadPool.execute(
            () -> {
              for (int j = 0; j < requests / threads; j++) {
                final long t = System.nanoTime();
                client.greet(j);
                recorder.record(t);
              }
            });
      }
      threadPool.shutdown();
      threadPool.awaitTermination(20, TimeUnit.MINUTES);

      final Snapshot stats = recorder.interval();
      final Duration duration = Duration.between(start, Instant.now());
      LOGGER.info(
          Markers.append("stats", stats).and(Markers.append("duration", duration.toString())),
          "{} requests in {} ({} req/sec)",
          stats.count(),
          duration,
          stats.throughput());
    } finally {
      client.shutdown();
    }
  } catch (SSLException | InterruptedException e) {
    LOGGER.error("Error running command", e);
  }
}
 
Example 19
Project: Rubus   File: HistoryChartGenerator.java   Source Code and License Vote up 4 votes
private double updateTime(double avg, TimeUnit timeUnit2) {
	if (timeUnit == TimeUnit.MILLISECONDS)
		avg = avg * 1000;
	// avg = TimeUnit.MILLISECONDS.toMillis(avg);

	if (timeUnit == TimeUnit.MICROSECONDS)

		avg = avg * 1000 * 1000;

	if (timeUnit == TimeUnit.NANOSECONDS)
		avg = avg * 1000 * 1000 * 1000;

	// avg = TimeUnit.MILLISECONDS.toNanos(avg);

	if (timeUnit == TimeUnit.SECONDS)
		; // already in sec

	return avg;
}
 
Example 20
Project: hadoop-oss   File: Configuration.java   Source Code and License Vote up 0 votes
TimeUnit unit() { return TimeUnit.MICROSECONDS; }