Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

The Problem

We had a service written in Java that retrieved a number from the database and returned it through a RESTful service to a Javascript client. The number was a long because of it’s large size. This had worked for a very long time. However, we noticed that when we had some very large numbers, the number started to be off by one. Specifically,

9164083756384584
9597642508289680

Those values were displayed as

9164083756384585
9597642508289681

In Java, we are used to overflow behavior being represented by a number turning negative because the signed bit is being used to represent data.

The Findings

We were able to verify that when we called the service with Postman, that we did see the correct value. The problem occurred when the Javascript client tried to parse the data. There was a specific line where the value was taken from the json to string marshalled object and it was converted to a string. This is where the problem was. After much searching and consulting with our Javascript experts, we ended up with ECMA 8.5 The Number Type. What an eye opener. This confirmed to us that the largest number that we could expect to be retrieved from our Java RESTful services was 2^53-1, not 2^63-1.

We had no idea that 9007199254740991 was the largest value that we could expect to be represented accurately in Javascript.

The Solution

Our solution was to add a property to the object that we were returning for marshalling by our Java RESTful services. We updated the service to have an additional property that was a String. Meaning that we would transition to return a String as our record IDs, instead of a long. This was fine, since arithmetic operations shouldn’t be performed on our object IDs anyway.

More Findings

We also found supporting information at

  • http://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE

October 4th, 2016

Posted In: ECMA, ECMAscript, Java, java ninja, Javaninja, javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com