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

The following examples show how to use java.time.Duration#ofNanos() . 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: AdaptiveDelay.java    From java-dcp-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the next delay in the backoff sequence.
 * <p>
 * If the cooldown duration has elapsed since the previous delay returned by this method,
 * the backoff sequence is reset and this method returns a duration of zero.
 */
public Duration calculate() {
  final long now = clock.nanoTime();

  synchronized (this) {
    final long nanosSinceLastEvent = now - lastEventNanos;
    final boolean cooldownElapsed = nanosSinceLastEvent >= cooldownNanos;

    if (cooldownElapsed) {
      attempt = 0;
      lastEventNanos = now;
      return Duration.ZERO;
    }

    final long delayNanos = delay.unit().toNanos(delay.calculate(++attempt));
    lastEventNanos = now + delayNanos;
    return Duration.ofNanos(delayNanos);
  }
}
 
Example 2
Source File: Subscriber.java    From stan.java with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a duration string of the form "98d 01h 23m 45s" into milliseconds.
 * 
 * @throws ParseException if the duration can't be parsed
 */
private static Duration parseDuration(String duration) throws ParseException {
    Matcher matcher = pattern.matcher(duration);

    long nanoseconds = 0L;

    if (matcher.find() && matcher.groupCount() == 4) {
        int days = Integer.parseInt(matcher.group(1));
        nanoseconds += TimeUnit.NANOSECONDS.convert(days, TimeUnit.DAYS);
        int hours = Integer.parseInt(matcher.group(2));
        nanoseconds += TimeUnit.NANOSECONDS.convert(hours, TimeUnit.HOURS);
        int minutes = Integer.parseInt(matcher.group(3));
        nanoseconds += TimeUnit.NANOSECONDS.convert(minutes, TimeUnit.MINUTES);
        int seconds = Integer.parseInt(matcher.group(4));
        nanoseconds += TimeUnit.NANOSECONDS.convert(seconds, TimeUnit.SECONDS);
        long nanos = Long.parseLong(matcher.group(5));
        nanoseconds += nanos;
    } else {
        throw new ParseException("Cannot parse duration " + duration, 0);
    }

    return Duration.ofNanos(nanoseconds);
}
 
Example 3
Source File: TimeDurationTest.java    From diirt with MIT License 5 votes vote down vote up
@Test
public void equals1() {
    Duration duration = Duration.ofNanos(1000000);
    assertThat(duration, equalTo(Duration.ofMillis(1)));
    assertThat(duration, equalTo(TimeDuration.ofSeconds(0.001)));
    assertThat(duration, equalTo(TimeDuration.ofMinutes(0.0000166666666667)));
    assertThat(duration, equalTo(TimeDuration.ofHours(0.0000002777777778)));
    assertThat(duration, not(equalTo(Duration.ofMillis(0))));
}
 
Example 4
Source File: Deadline.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the time left between the deadline and now. If no time is left, a {@link TimeoutException} will be thrown.
 *
 * @throws TimeoutException if no time is left
 */
public Duration timeLeftIfAny() throws TimeoutException {
	long nanos = Math.subtractExact(timeNanos, System.nanoTime());
	if (nanos <= 0) {
		throw new TimeoutException();
	}
	return Duration.ofNanos(nanos);
}
 
Example 5
Source File: TCKYearMonth.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name="plus_TemporalAmount")
Object[][] data_plus_TemporalAmount() {
    return new Object[][] {
        {YearMonth.of(1, 1), Period.ofYears(1), YearMonth.of(2, 1), null},
        {YearMonth.of(1, 1), Period.ofYears(-12), YearMonth.of(-11, 1), null},
        {YearMonth.of(1, 1), Period.ofYears(0), YearMonth.of(1, 1), null},
        {YearMonth.of(999999999, 12), Period.ofYears(0), YearMonth.of(999999999, 12), null},
        {YearMonth.of(-999999999, 1), Period.ofYears(0), YearMonth.of(-999999999, 1), null},
        {YearMonth.of(0, 1), Period.ofYears(-999999999), YearMonth.of(-999999999, 1), null},
        {YearMonth.of(0, 12), Period.ofYears(999999999), YearMonth.of(999999999, 12), null},

        {YearMonth.of(1, 1), Period.ofMonths(1), YearMonth.of(1, 2), null},
        {YearMonth.of(1, 1), Period.ofMonths(-12), YearMonth.of(0, 1), null},
        {YearMonth.of(1, 1), Period.ofMonths(121), YearMonth.of(11, 2), null},
        {YearMonth.of(1, 1), Period.ofMonths(0), YearMonth.of(1, 1), null},
        {YearMonth.of(999999999, 12), Period.ofMonths(0), YearMonth.of(999999999, 12), null},
        {YearMonth.of(-999999999, 1), Period.ofMonths(0), YearMonth.of(-999999999, 1), null},
        {YearMonth.of(-999999999, 2), Period.ofMonths(-1), YearMonth.of(-999999999, 1), null},
        {YearMonth.of(999999999, 11), Period.ofMonths(1), YearMonth.of(999999999, 12), null},

        {YearMonth.of(1, 1), Period.ofYears(1).withMonths(2), YearMonth.of(2, 3), null},
        {YearMonth.of(1, 1), Period.ofYears(-12).withMonths(-1), YearMonth.of(-12, 12), null},

        {YearMonth.of(1, 1), Period.ofMonths(2).withYears(1), YearMonth.of(2, 3), null},
        {YearMonth.of(1, 1), Period.ofMonths(-1).withYears(-12), YearMonth.of(-12, 12), null},

        {YearMonth.of(1, 1), Period.ofDays(365), null, DateTimeException.class},
        {YearMonth.of(1, 1), Duration.ofDays(365), null, DateTimeException.class},
        {YearMonth.of(1, 1), Duration.ofHours(365*24), null, DateTimeException.class},
        {YearMonth.of(1, 1), Duration.ofMinutes(365*24*60), null, DateTimeException.class},
        {YearMonth.of(1, 1), Duration.ofSeconds(365*24*3600), null, DateTimeException.class},
        {YearMonth.of(1, 1), Duration.ofNanos(365*24*3600*1000000000), null, DateTimeException.class},
    };
}
 
Example 6
Source File: IosBaseAppium.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * ��סҳ�水��Ļ�������ϻ���(��ָ���£�ҳ������)
 * @param driver appium��ʼ������
 * @param second ����ʱ��
 * @param num ��������
 */
public static void swipePageUp(IOSDriver<IOSElement> driver, Double second, int num) {
	int nanos = (int) (second * 1000);
	Duration duration = Duration.ofNanos(nanos);
	int width = driver.manage().window().getSize().width;
	int height = driver.manage().window().getSize().height;
	IOSTouchAction action = new IOSTouchAction(driver);
	
	for (int i = 0; i <= num; i++) {
		action.press(PointOption.point(width / 2, 20)).waitAction(WaitOptions.waitOptions(duration))
				.moveTo(PointOption.point(width / 2, height-20)).release().perform();
	}
}
 
Example 7
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testTryEnterWithInterruptDuringTimeout() throws InterruptedException {
    Duration expectedWaitTime = Duration.ofMillis(2000);
    BulkheadConfig config = BulkheadConfig.custom()
        .maxConcurrentCalls(1)
        .maxWaitDuration(expectedWaitTime)
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", config);

    AtomicBoolean interruptedWithoutCodeFlowBreak = new AtomicBoolean(false);
    boolean entered = bulkhead.tryEnterBulkhead();
    Thread subTestRoutine = new Thread(() -> {
        long start = System.nanoTime();
        boolean acquired = bulkhead.tryAcquirePermission();
        Duration actualWaitTime = Duration.ofNanos(System.nanoTime() - start);
        assertThat(acquired).isFalse();
        assertThat(actualWaitTime).isLessThan(expectedWaitTime);
        assertThat(Thread.currentThread().isInterrupted()).isTrue();
        interruptedWithoutCodeFlowBreak.set(true);
    });
    subTestRoutine.setDaemon(true);
    subTestRoutine.start();

    await().atMost(expectedWaitTime.dividedBy(2).toMillis(), MILLISECONDS)
        .pollInterval(expectedWaitTime.dividedBy(100).toMillis(), MILLISECONDS)
        .until(() -> subTestRoutine.getState() == Thread.State.TIMED_WAITING);
    subTestRoutine.interrupt();
    await().atMost(expectedWaitTime.dividedBy(2).toMillis(), MILLISECONDS)
        .pollInterval(expectedWaitTime.dividedBy(100).toMillis(), MILLISECONDS)
        .until(() -> subTestRoutine.getState() == Thread.State.TERMINATED);
    assertThat(entered).isTrue();
    assertThat(interruptedWithoutCodeFlowBreak.get()).isTrue();
    assertThat(subTestRoutine.isAlive()).isFalse();
}
 
Example 8
Source File: AndroidBaseAppium.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * ��סҳ�水��Ļ�������ϻ���(��ָ���£�ҳ������)
 * @param driver appium��ʼ������
 * @param second ����ʱ��
 * @param num ��������
 */
public static void swipePageUp(AndroidDriver<AndroidElement> driver, Double second, int num) {
	int nanos = (int) (second * 1000);
	Duration duration = Duration.ofNanos(nanos);
	int width = driver.manage().window().getSize().width;
	int height = driver.manage().window().getSize().height;
	AndroidTouchAction action = new AndroidTouchAction(driver);

	for (int i = 0; i <= num; i++) {
		action.press(PointOption.point(width / 2, 20)).waitAction(WaitOptions.waitOptions(duration))
				.moveTo(PointOption.point(width / 2, height-20)).release().perform();
	}
}
 
Example 9
Source File: CircuitBreakerStateMachine.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
private void publishSuccessEvent(final long duration, TimeUnit durationUnit) {
    final CircuitBreakerOnSuccessEvent event = new CircuitBreakerOnSuccessEvent(name,
        Duration.ofNanos(durationUnit.toNanos(duration)));
    publishEventIfPossible(event);
}
 
Example 10
Source File: Split.java    From pikatimer with GNU General Public License v3.0 4 votes vote down vote up
public void setSplitCutoff(Long c) {
    if(c != null) {
        //Fix this to watch for parse exceptions
        splitCutoff = Duration.ofNanos(c);
    }
}
 
Example 11
Source File: TCKDuration.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void factory_nanos_nanos() {
    Duration test = Duration.ofNanos(1);
    assertEquals(test.getSeconds(), 0);
    assertEquals(test.getNano(), 1);
}
 
Example 12
Source File: TCKDuration.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void factory_nanos_max() {
    Duration test = Duration.ofNanos(Long.MAX_VALUE);
    assertEquals(test.getSeconds(), Long.MAX_VALUE / 1000000000);
    assertEquals(test.getNano(), Long.MAX_VALUE % 1000000000);
}
 
Example 13
Source File: TCKDuration.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void factory_nanos_nanos() {
    Duration test = Duration.ofNanos(1);
    assertEquals(test.getSeconds(), 0);
    assertEquals(test.getNano(), 1);
}
 
Example 14
Source File: TimeDurationTest.java    From diirt with MIT License 4 votes vote down vote up
@Test
public void nanos2() {
    Duration duration = Duration.ofNanos(1234567890L);
    assertThat(duration.getNano(), equalTo(234567890));
    assertThat(duration.getSeconds(), equalTo(1L));
}
 
Example 15
Source File: DCmdDump.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Execute JFR.dump.
 *
 * @param name name or id of the recording to dump, or <code>null</code> to dump everything
 *
 * @param filename file path where recording should be written, not null
 * @param maxAge how far back in time to dump, may be null
 * @param maxSize how far back in size to dump data from, may be null
 * @param begin point in time to dump data from, may be null
 * @param end point in time to dump data to, may be null
 * @param pathToGcRoots if Java heap should be swept for reference chains
 *
 * @return result output
 *
 * @throws DCmdException if the dump could not be completed
 */
public String execute(String name, String filename, Long maxAge, Long maxSize, String begin, String end, Boolean pathToGcRoots) throws DCmdException {
    if (Logger.shouldLog(LogTag.JFR_DCMD, LogLevel.DEBUG)) {
        Logger.log(LogTag.JFR_DCMD, LogLevel.DEBUG,
                "Executing DCmdDump: name=" + name +
                ", filename=" + filename +
                ", maxage=" + maxAge +
                ", maxsize=" + maxSize +
                ", begin=" + begin +
                ", end" + end +
                ", path-to-gc-roots=" + pathToGcRoots);
    }

    if (FlightRecorder.getFlightRecorder().getRecordings().isEmpty()) {
        throw new DCmdException("No recordings to dump from. Use JFR.start to start a recording.");
    }

    if (maxAge != null) {
        if (end != null || begin != null) {
            throw new DCmdException("Dump failed, maxage can't be combined with begin or end.");
        }

        if (maxAge < 0) {
            throw new DCmdException("Dump failed, maxage can't be negative.");
        }
        if (maxAge == 0) {
            maxAge = Long.MAX_VALUE / 2; // a high value that won't overflow
        }
    }

    if (maxSize!= null) {
        if (maxSize < 0) {
            throw new DCmdException("Dump failed, maxsize can't be negative.");
        }
        if (maxSize == 0) {
            maxSize = Long.MAX_VALUE / 2; // a high value that won't overflow
        }
    }

    Instant beginTime = parseTime(begin, "begin");
    Instant endTime = parseTime(end, "end");

    if (beginTime != null && endTime != null) {
        if (endTime.isBefore(beginTime)) {
            throw new DCmdException("Dump failed, begin must preceed end.");
        }
    }

    Duration duration = null;
    if (maxAge != null) {
        duration = Duration.ofNanos(maxAge);
        beginTime = Instant.now().minus(duration);
    }
    Recording recording = null;
    if (name != null) {
        recording = findRecording(name);
    }
    PlatformRecorder recorder = PrivateAccess.getInstance().getPlatformRecorder();
    synchronized (recorder) {
        dump(recorder, recording, name, filename, maxSize, pathToGcRoots, beginTime, endTime);
    }
    return getResult();
}
 
Example 16
Source File: TCKDuration.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void factory_nanos_max() {
    Duration test = Duration.ofNanos(Long.MAX_VALUE);
    assertEquals(test.getSeconds(), Long.MAX_VALUE / 1000000000);
    assertEquals(test.getNano(), Long.MAX_VALUE % 1000000000);
}
 
Example 17
Source File: TimeDuration.java    From phoebus with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * A new duration in hours.
 *
 * @param hour hours
 * @return a new duration
 */
public static Duration ofHours(double hour) {
    return Duration.ofNanos((long) (hour * 60 * 60 * NANOSEC_IN_SEC));
}
 
Example 18
Source File: Deadline.java    From flink with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the time left between the deadline and now. The result is negative if the deadline
 * has passed.
 */
public Duration timeLeft() {
	return Duration.ofNanos(Math.subtractExact(timeNanos, System.nanoTime()));
}
 
Example 19
Source File: RecordedEvent.java    From dragonwell8_jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns the duration of the event, measured in nanoseconds.
 *
 * @return the duration in nanoseconds, not {@code null}
 */
public Duration getDuration() {
    return Duration.ofNanos(endTime - startTime);
}
 
Example 20
Source File: TimeDuration.java    From phoebus with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * A new duration in minutes.
 *
 * @param min minutes
 * @return a new duration
 */
public static Duration ofMinutes(double min) {
    return Duration.ofNanos((long) (min * 60 * NANOSEC_IN_SEC));
}