BigDecimal.valueOf caching mechanism

I heard that the BigDecimal.valueOf() method is better than calling new BigDecimal() because it caches common values. I wanted to know how the caching mechanism of valueOf works.

Jon Skeet
people
quotationmark

Looking at the JDK 1.8 sources, it looks like it's just a static array which is initialized as part of class initialization - it only caches the values 0 to 10 inclusive, but that's an implementation detail. For example, given dasblinkenlight's post, it looks like earlier versions only cached 0 and 1.

For more detail - and to make sure you're getting information about the JDK which you're actually running - look at the source of the JDK you're using for yourself - most IDEs will open the relevant source code automatically, if they detect the source archive has been included in your JDK installation. Of course, if you're using a different JRE at execution time, you'd need to validate that too.

It's easy to tell whether or not a value has been cached, based on reference equality. Here's a short but complete program which finds the first non-negative value which isn't cached:

import java.math.BigDecimal;

public class Test {
    public static void main(String[] args) {
        for (long x = 0; x < Long.MAX_VALUE; x++) {
            if (BigDecimal.valueOf(x) != BigDecimal.valueOf(x)) {
                System.out.println("Value for " + x + " wasn't cached");
                break;
            }
        }
    }
}

On my machine with Java 8, the output is:

Value for 11 wasn't cached

Of course, an implementation could always cache the most recently requested value, in which case the above code would run for a very long time and then finish with no output...

people

See more on this question at Stackoverflow