Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8074032

Instant.ofEpochMilli(millis).toEpochMilli() can throw arithmetic overflow in toEpochMilli()

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P3 P3
    • 9
    • None
    • core-libs
    • None
    • b54

        The following test:

                for (Object[] test : new Object[][] {
                    {"Long.MAX_VALUE",Long.MAX_VALUE},
                    {"Long.MAX_VALUE-1",Long.MAX_VALUE-1},
                    {"1",1L},
                    {"0", 0L},
                    {"-1",-1L},
                    {"Long.MIN_VALUE+1",Long.MIN_VALUE+1},
                    {"Long.MIN_VALUE",Long.MIN_VALUE}
                    }) {

                    long millis = (Long)test[1];
                    System.err.println("Testing with " + test[0] +": "+millis+"L");
                    Instant i1 = Instant.ofEpochMilli(millis);
                    System.err.println("Instant.ofEpochMilli(): " + i1);
                    long seconds = i1.getEpochSecond();
                    System.err.println("Instant.getEpochSecond(): " + seconds);
                    System.err.println("millis/1000: " + millis/1000);

                    long millis2 = i1.toEpochMilli();
                    System.err.println("Instant.toEpochMilli(): " + millis2+"L");
                    if (millis2 != millis) {
                        throw new RuntimeException("Test failed for " + test[0]
                                + "\n\texpected: "+millis+"L"
                                + "\n\tactual: "+millis2+"L");
                    }
                }

        causes an arithmetic overflow for Long.MIN_VALUE+1 and Long.MIN_VALUE.

        Exception in thread "main" java.lang.ArithmeticException: long overflow
        at java.lang.Math.multiplyExact(Math.java:915)
        at java.time.Instant.toEpochMilli(Instant.java:1232)

              dfuchs Daniel Fuchs
              dfuchs Daniel Fuchs
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Created:
                Updated:
                Resolved: