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

Instant.toEpochMilli() silently overflows

    XMLWordPrintable

Details

    • Bug
    • Resolution: Fixed
    • P4
    • 9
    • 8u45, 9
    • core-libs
    • b77
    • x86
    • windows_8

    Backports

      Description

        FULL PRODUCT VERSION :
        1.8.0_45-b15

        ADDITIONAL OS VERSION INFORMATION :
        Any OS

        A DESCRIPTION OF THE PROBLEM :
        This code should throw an ArithmeticException but silently overflows:

            Instant tooMuch = Instant.ofEpochSecond(Long.MAX_VALUE / 1000, 809_000_000);
            System.out.println(tooMuch.toEpochMilli()); //prints -9223372036854775807

        The problem is in the code of toEpochMilli:

            public long toEpochMilli() {
                long millis = Math.multiplyExact(seconds, 1000);
                return millis + nanos / 1000_000;
            }

        which should probably be:

            public long toEpochMilli() {
                long millis = Math.multiplyExact(seconds, 1000);
                return Math.addExact(millis, nanos / 1000_000);
            }

        EXPECTED VERSUS ACTUAL BEHAVIOR :
        EXPECTED -
        The code should throw an ArithmeticException
        ACTUAL -
        The result is a negative number due to overflow

        REPRODUCIBILITY :
        This bug can be reproduced always.

        ---------- BEGIN SOURCE ----------
          public static void main(String args[]) {
            Instant tooMuch = Instant.ofEpochSecond(Long.MAX_VALUE / 1000, 809_000_000);
            System.out.println(tooMuch.toEpochMilli()); //prints -9223372036854775807
          }
        ---------- END SOURCE ----------

        Attachments

          Issue Links

            Activity

              People

                rriggs Roger Riggs
                webbuggrp Webbug Group
                Votes:
                0 Vote for this issue
                Watchers:
                5 Start watching this issue

                Dates

                  Created:
                  Updated:
                  Resolved: