Java Code Examples for java.time.Duration#toNanos()
The following examples show how to use
java.time.Duration#toNanos() .
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 File: AssertSubscriber.java From rsocket-java with Apache License 2.0 | 6 votes |
/** * 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
Source File: Utils.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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
Source File: AtomicRateLimiterTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 File: Refill.java From bucket4j with Apache License 2.0 | 6 votes |
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
Source File: Utils.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
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
Source File: InfoTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@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 File: TimeUtils.java From flink with Apache License 2.0 | 5 votes |
/** * 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
Source File: BoundedExponentialBackoff.java From flink-statefun with Apache License 2.0 | 5 votes |
@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
Source File: ExpiringCacheAsync.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
/** * 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
Source File: MoreSuppliers.java From more-lambdas-java with Artistic License 2.0 | 5 votes |
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
Source File: RedisImpl.java From core-ng-project with Apache License 2.0 | 4 votes |
public void slowOperationThreshold(Duration threshold) { slowOperationThresholdInNanos = threshold.toNanos(); }
Example 12
Source File: DBConfig.java From core-ng-project with Apache License 2.0 | 4 votes |
public void slowOperationThreshold(Duration threshold) { database.slowOperationThresholdInNanos = threshold.toNanos(); }
Example 13
Source File: TopBuilder.java From rolling-metrics with Apache License 2.0 | 4 votes |
@Override public Top create(int size, Duration latencyThreshold, int maxDescriptionLength, Clock clock) { return new UniformTop(size, latencyThreshold.toNanos(), maxDescriptionLength); }
Example 14
Source File: TCKDuration.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=ArithmeticException.class) public void test_toNanos_tooBig() { Duration test = Duration.ofSeconds(0, Long.MAX_VALUE).plusNanos(1); test.toNanos(); }
Example 15
Source File: TimerCompletable.java From servicetalk with Apache License 2.0 | 4 votes |
TimerCompletable(final Duration delay, final Executor timeoutExecutor) { this.timeoutExecutor = requireNonNull(timeoutExecutor); this.delayNs = delay.toNanos(); }
Example 16
Source File: TCKDuration.java From hottub with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=ArithmeticException.class) public void test_toNanos_tooBig() { Duration test = Duration.ofSeconds(0, Long.MAX_VALUE).plusNanos(1); test.toNanos(); }
Example 17
Source File: TCKDuration.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=ArithmeticException.class) public void test_toNanos_tooBig() { Duration test = Duration.ofSeconds(0, Long.MAX_VALUE).plusNanos(1); test.toNanos(); }
Example 18
Source File: DBConfig.java From core-ng-project with Apache License 2.0 | 4 votes |
public void longTransactionThreshold(Duration threshold) { database.operation.transactionManager.longTransactionThresholdInNanos = threshold.toNanos(); }
Example 19
Source File: TCKDuration.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=ArithmeticException.class) public void test_toNanos_tooSmall() { Duration test = Duration.ofSeconds(0, Long.MIN_VALUE).minusNanos(1); test.toNanos(); }
Example 20
Source File: InfoTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 3 votes |
/** * 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; }