Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NumberFormat.getInstance guaranteed to create a new instance?

Tags:

java

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?

like image 827
Paul Hollingsworth Avatar asked Aug 10 '12 10:08

Paul Hollingsworth


1 Answers

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.

like image 53
JB Nizet Avatar answered Sep 17 '22 15:09

JB Nizet