Java Code Examples for java.time.Duration#toNanos()

The following examples show how to use java.time.Duration#toNanos() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: rsocket-java   File: AssertSubscriber.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Blocking method that waits until {@code conditionSupplier} returns true, or if it does not
 * before the specified timeout, throws an {@link AssertionError} with the specified error message
 * supplier.
 *
 * @param timeout the timeout duration
 * @param errorMessageSupplier the error message supplier
 * @param conditionSupplier condition to break out of the wait loop
 * @throws AssertionError
 */
public static void await(
    Duration timeout, Supplier<String> errorMessageSupplier, BooleanSupplier conditionSupplier) {

  Objects.requireNonNull(errorMessageSupplier);
  Objects.requireNonNull(conditionSupplier);
  Objects.requireNonNull(timeout);

  long timeoutNs = timeout.toNanos();
  long startTime = System.nanoTime();
  do {
    if (conditionSupplier.getAsBoolean()) {
      return;
    }
    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new RuntimeException(e);
    }
  } while (System.nanoTime() - startTime < timeoutNs);
  throw new AssertionError(errorMessageSupplier.get());
}
 
Example 2
public static String formatTimespan(Duration dValue, String separation) {
    if (dValue == null) {
        return "0";
    }
    long value = dValue.toNanos();
    TimespanUnit result = TimespanUnit.NANOSECONDS;
    for (TimespanUnit unit : TimespanUnit.values()) {
        result = unit;
        long amount = unit.amount;
        if (result == TimespanUnit.DAYS || value < amount || value % amount != 0) {
            break;
        }
        value /= amount;
    }
    return String.format("%d%s%s", value, separation, result.text);
}
 
Example 3
@Test
public void reservePermissionsUpfront() throws Exception {
    final int limitForPeriod = 3;
    final int tasksNum = 9;
    Duration limitRefreshPeriod = Duration.ofMillis(10);
    Duration timeoutDuration = Duration.ofMillis(12);
    long cycleInNanos = limitRefreshPeriod.toNanos();

    setup(limitRefreshPeriod, timeoutDuration, limitForPeriod);
    setTimeOnNanos(cycleInNanos);

    ArrayList<Long> timesToWait = new ArrayList<>();
    for (int i = 0; i < tasksNum; i++) {
        setTimeOnNanos(cycleInNanos + i + 1);
        long timeToWait = rateLimiter.reservePermission(1);
        timesToWait.add(timeToWait);
    }
    then(timesToWait).containsExactly(
        0L, 0L, 0L,
        cycleInNanos - 4, cycleInNanos - 5, cycleInNanos - 6,
        -1L, -1L, -1L
    );
}
 
Example 4
Source Project: bucket4j   File: Refill.java    License: Apache License 2.0 6 votes vote down vote up
private Refill(long tokens, Duration period, boolean refillIntervally, long timeOfFirstRefillMillis, boolean useAdaptiveInitialTokens) {
    if (period == null) {
        throw BucketExceptions.nullRefillPeriod();
    }
    if (tokens <= 0) {
        throw BucketExceptions.nonPositivePeriodTokens(tokens);
    }
    this.periodNanos = period.toNanos();
    if (periodNanos <= 0) {
        throw BucketExceptions.nonPositivePeriod(periodNanos);
    }
    if (tokens > periodNanos) {
        throw BucketExceptions.tooHighRefillRate(periodNanos, tokens);
    }

    this.tokens = tokens;
    this.refillIntervally = refillIntervally;
    this.timeOfFirstRefillMillis = timeOfFirstRefillMillis;
    this.useAdaptiveInitialTokens = useAdaptiveInitialTokens;
}
 
Example 5
public static String formatTimespan(Duration dValue, String separation) {
    if (dValue == null) {
        return "0";
    }
    long value = dValue.toNanos();
    TimespanUnit result = TimespanUnit.NANOSECONDS;
    for (TimespanUnit unit : TimespanUnit.values()) {
        result = unit;
        long amount = unit.amount;
        if (result == TimespanUnit.DAYS || value < amount || value % amount != 0) {
            break;
        }
        value /= amount;
    }
    return String.format("%d%s%s", value, separation, result.text);
}
 
Example 6
@Test
public static void test5() {
    ProcessHandle self = ProcessHandle.current();
    Random r = new Random();
    for (int i = 0; i < 30; i++) {
        Instant end = Instant.now().plusMillis(500L);
        while (end.isBefore(Instant.now())) {
            // burn the cpu time checking the time
            long x = r.nextLong();
        }
        if (self.info().totalCpuDuration().isPresent()) {
            Duration totalCpu = self.info().totalCpuDuration().get();
            long infoTotalCputime = totalCpu.toNanos();
            long beanCputime = ProcessUtil.MXBeanCpuTime().toNanos();
            System.out.printf(" infoTotal: %12d, beanCpu: %12d, diff: %12d%n",
                    infoTotalCputime, beanCputime, beanCputime - infoTotalCputime);
        } else {
            break;  // nothing to compare; continue
        }
    }
}
 
Example 7
Source Project: flink   File: TimeUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Pretty prints the duration as a lowest granularity unit that does not lose precision.
 *
 * <p>Examples:
 * <pre>{@code
 * Duration.ofMilliseconds(60000) will be printed as 1 min
 * Duration.ofHours(1).plusSeconds(1) will be printed as 3601 s
 * }</pre>
 *
 * <b>NOTE:</b> It supports only durations that fit into long.
 */
public static String formatWithHighestUnit(Duration duration) {
	long nanos = duration.toNanos();

	List<TimeUnit> orderedUnits = Arrays.asList(
			TimeUnit.NANOSECONDS,
			TimeUnit.MICROSECONDS,
			TimeUnit.MILLISECONDS,
			TimeUnit.SECONDS,
			TimeUnit.MINUTES,
			TimeUnit.HOURS,
			TimeUnit.DAYS);

	TimeUnit highestIntegerUnit = IntStream.range(0, orderedUnits.size())
		.sequential()
		.filter(idx -> nanos % orderedUnits.get(idx).unit.getDuration().toNanos() != 0)
		.boxed()
		.findFirst()
		.map(idx -> {
			if (idx == 0) {
				return orderedUnits.get(0);
			} else {
				return orderedUnits.get(idx - 1);
			}
		}).orElse(TimeUnit.MILLISECONDS);

	return String.format(
		"%d %s",
		nanos / highestIntegerUnit.unit.getDuration().toNanos(),
		highestIntegerUnit.getLabels().get(0));
}
 
Example 8
@VisibleForTesting
BoundedExponentialBackoff(
    Timer timer, Duration initialBackoffDuration, Duration maxRequestDuration) {
  this.timer = Objects.requireNonNull(timer);
  this.requestStartTimeInNanos = timer.now();
  this.maxRequestDurationInNanos = maxRequestDuration.toNanos();
  this.nextSleepTimeNanos = initialBackoffDuration.toNanos();
}
 
Example 9
/**
 * Create a new instance.
 *
 * @param expiry the duration in milliseconds for how long the value stays valid. Must be positive.
 * @throws IllegalArgumentException For an expire value <=0.
 */
public ExpiringCacheAsync(Duration expiry) {
    if (expiry.isNegative() || expiry.isZero()) {
        throw new IllegalArgumentException("Cache expire time must be greater than 0");
    }
    this.expiry = expiry.toNanos();
}
 
Example 10
private void tryWait(@Nullable Duration maxWaitFromFirstCall) {
    if (maxWaitFromFirstCall == null) {
        return;
    }
    long passedDuration = nanoTime() - firstInitNano;
    long maxWaitDuration = maxWaitFromFirstCall.toNanos();
    long needWaitDuration = maxWaitDuration - passedDuration;
    if (needWaitDuration > 0) {
        awaitUninterruptibly(latch, needWaitDuration, NANOSECONDS);
    }
}
 
Example 11
@Test(expectedExceptions=ArithmeticException.class)
public void test_toNanos_tooBig() {
    Duration test = Duration.ofSeconds(0, Long.MAX_VALUE).plusNanos(1);
    test.toNanos();
}
 
Example 12
@Test(expectedExceptions=ArithmeticException.class)
public void test_toNanos_tooSmall() {
    Duration test = Duration.ofSeconds(0, Long.MIN_VALUE).minusNanos(1);
    test.toNanos();
}
 
Example 13
Source Project: core-ng-project   File: DBConfig.java    License: Apache License 2.0 4 votes vote down vote up
public void longTransactionThreshold(Duration threshold) {
    database.operation.transactionManager.longTransactionThresholdInNanos = threshold.toNanos();
}
 
Example 14
Source Project: core-ng-project   File: RedisImpl.java    License: Apache License 2.0 4 votes vote down vote up
public void slowOperationThreshold(Duration threshold) {
    slowOperationThresholdInNanos = threshold.toNanos();
}
 
Example 15
Source Project: hottub   File: TCKDuration.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=ArithmeticException.class)
public void test_toNanos_tooBig() {
    Duration test = Duration.ofSeconds(0, Long.MAX_VALUE).plusNanos(1);
    test.toNanos();
}
 
Example 16
Source Project: servicetalk   File: TimerCompletable.java    License: Apache License 2.0 4 votes vote down vote up
TimerCompletable(final Duration delay,
                 final Executor timeoutExecutor) {
    this.timeoutExecutor = requireNonNull(timeoutExecutor);
    this.delayNs = delay.toNanos();
}
 
Example 17
@Test(expectedExceptions=ArithmeticException.class)
public void test_toNanos_tooBig() {
    Duration test = Duration.ofSeconds(0, Long.MAX_VALUE).plusNanos(1);
    test.toNanos();
}
 
Example 18
Source Project: rolling-metrics   File: TopBuilder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Top create(int size, Duration latencyThreshold, int maxDescriptionLength, Clock clock) {
    return new UniformTop(size, latencyThreshold.toNanos(), maxDescriptionLength);
}
 
Example 19
Source Project: core-ng-project   File: DBConfig.java    License: Apache License 2.0 4 votes vote down vote up
public void slowOperationThreshold(Duration threshold) {
    database.slowOperationThresholdInNanos = threshold.toNanos();
}
 
Example 20
/**
 * Check two Durations, the second should be greater than the first or
 * within the supplied Epsilon.
 * @param d1 a Duration - presumed to be shorter
 * @param d2 a 2nd Duration - presumed to be greater (or within Epsilon)
 * @param epsilon Epsilon the amount of overlap allowed
 * @return true if d2 is greater than d1 or within epsilon, false otherwise
 */
static boolean checkEpsilon(Duration d1, Duration d2, Duration epsilon) {
    if (d1.toNanos() <= d2.toNanos()) {
        return true;
    }
    Duration diff = d1.minus(d2).abs();
    return diff.compareTo(epsilon) <= 0;
}