4

调用 JDKInstant.toEpochMilli()可能会导致算术上溢/下溢(例如Instant.MAX.toEpochMilli()Instant.MIN.toEpochMilli())。我正在寻找一种简单的方法来避免算术溢出并简单地使用Long.MAX_VALUE. 这是我当前的代码。

long seconds, millis;

seconds = deadline.getEpochSecond();

if (seconds > Long.MAX_VALUE / 1000 - 1)
   millis = Long.MAX_VALUE;
else if (seconds < Long.MIN_VALUE / 1000 + 1)
   millis = Long.MIN_VALUE;
else
   millis = deadline.toEpochMilli();

似乎必须有一种更清洁/更清晰的方式来实现这一点。你将如何实现这个逻辑?

我必须担心上溢/下溢,因为Instant.MAXInstant.MIN被传递给此代码所在的方法。

4

2 回答 2

6

您可以使用java.lang.Math.addExact. ArithmeticException 如果发生溢出,它将抛出一个。它是在 Java 8 中添加的。

编辑

好的,再想一想这个问题,我想我有一个很好的解决方案:

private Instant capped(Instant instant) {
    Instant[] instants = {Instant.ofEpochMilli(Long.MIN_VALUE), instant, Instant.ofEpochMilli(Long.MAX_VALUE)};
    Arrays.sort(instants);
    return instants[1];
}

此方法将返回一个永远不会溢出的 Instant toEpochMilli()

将您的逻辑简化为:

millis = capped(deadline).toEpochMilli();
于 2017-04-19T20:48:18.413 回答
1

toEpochMilli在溢出的情况下引发异常,因此您可以捕获该异常:

try {
  millis = deadline.toEpochMillis();
} catch (AritmeticException ignore) {
  millis = deadline.getEpochSecond() < 0 ? Long.MIN_VALUE : Long.MAX_VALUE;
}

这段代码比问题中写的更简单、更安全。它更安全,因为它不会尝试重新实现内部的边界逻辑toEpochMillis()

抛出和捕获异常可能存在性能问题。这取决于抛出异常的频率。如果大部分时间都抛出异常,那么除非 JVM 可以优化它,否则它的性能会更差。如果很少抛出异常,那么性能会很好。

JVM 或许能够优化这一点,但也许不能。

于 2017-04-18T14:30:26.070 回答