Consider the following code:
NumberFormat format = NumberFormat.getInstance();
format.setMinimumFractionDigits(spotDecimalPlaces);
format.setMaximumFractionDigits(spotDecimalPlaces);
Is it "safe"? Is NumberFormat.getInstance()
guaranteed to return a new NumberFormat
object each time?
Or is there a possibility that getInstance()
returns the same instance? (in which case this code would affect everywhere else in the JVM that happens to use getInstance
...)
Looking at the source code it seems like it returns a new instance each time. The JavaDoc is frustratingly vague on the matter.
If the above code really is "safe", then it seems to me that getInstance()
is a poor name for this method - that it should have been called createInstance()
.
Is NumberFormat.getInstance()
guaranteed to always return a new instance?
Yes, it's safe. The code either get an instance from a NumberFormatProvider
(which must, according to the documentation, return a new instance), or it creates a new instance of DecimalFormat
.
Logically, since NumberFormat
is mutable, returning the same instance or cached instances would make the method completely unusable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With