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

Instant.toEpochMilli() silently overflows

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: P4
    • Resolution: Fixed
    • Affects Version/s: 8u45, 9
    • Fix Version/s: 9
    • Component/s: core-libs
    • Labels:
    • Subcomponent:
    • Resolved In Build:
      b77
    • CPU:
      x86
    • OS:
      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

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

                  Dates

                  • Created:
                    Updated:
                    Resolved: