From 9c91c5d589bdd3d34ce9596cbc4fe322bae9a265 Mon Sep 17 00:00:00 2001 From: igerasim Date: Sat, 8 Aug 2015 03:25:36 +0300 Subject: [PATCH] 8133022: Instant.toEpochMilli() silently overflows Reviewed-by: lancea, chegar, simonis, dfuchs, igerasim --- src/share/classes/java/time/Instant.java | 4 ++-- test/java/time/tck/java/time/TCKInstant.java | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/share/classes/java/time/Instant.java b/src/share/classes/java/time/Instant.java index a660b1d3f..9b9efa582 100644 --- a/src/share/classes/java/time/Instant.java +++ b/src/share/classes/java/time/Instant.java @@ -1232,10 +1232,10 @@ public final class Instant if (seconds < 0 && nanos > 0) { long millis = Math.multiplyExact(seconds+1, 1000); long adjustment = nanos / 1000_000 - 1000; - return millis + adjustment; + return Math.addExact(millis, adjustment); } else { long millis = Math.multiplyExact(seconds, 1000); - return millis + nanos / 1000_000; + return Math.addExact(millis, nanos / 1000_000); } } diff --git a/test/java/time/tck/java/time/TCKInstant.java b/test/java/time/tck/java/time/TCKInstant.java index ee3898e1b..3fbead471 100644 --- a/test/java/time/tck/java/time/TCKInstant.java +++ b/test/java/time/tck/java/time/TCKInstant.java @@ -112,6 +112,8 @@ import org.testng.annotations.Test; /** * Test Instant. + * + * @bug 8133022 */ @Test public class TCKInstant extends AbstractDateTimeTest { @@ -1928,6 +1930,16 @@ public class TCKInstant extends AbstractDateTimeTest { Instant.ofEpochSecond(Long.MIN_VALUE / 1000 - 1).toEpochMilli(); } + @Test(expectedExceptions=ArithmeticException.class) + public void test_toEpochMillis_overflow() { + Instant.ofEpochSecond(Long.MAX_VALUE / 1000, 809_000_000).toEpochMilli(); + } + + @Test(expectedExceptions=ArithmeticException.class) + public void test_toEpochMillis_overflow2() { + Instant.ofEpochSecond(-9223372036854776L, 1).toEpochMilli(); + } + //----------------------------------------------------------------------- // compareTo() //----------------------------------------------------------------------- -- GitLab