8133022: Instant.toEpochMilli() silently overflows

Reviewed-by: lancea, chegar, simonis, dfuchs, igerasim
This commit is contained in:
Roger Riggs 2015-08-06 14:35:04 -04:00
parent 8145a4b457
commit e2f7de320c
2 changed files with 14 additions and 2 deletions

View File

@ -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);
}
}

View File

@ -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()
//-----------------------------------------------------------------------