调用 JDK Instant.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.MAX
和 Instant.MIN
被传递到此代码所在的方法。
最佳答案
您可以使用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];
}
此方法将返回一个在 toEpochMilli()
上永远不会溢出的 Instant。
将逻辑简化为:
millis = capped(deadline).toEpochMilli();
关于java - 避免 Instant.toEpochMilli() 算术溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43460515/