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.
From the NumberFormat
page
Synchronization
Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
This indirectly states that the method creates a new instance with every call. Because, since NumberFormat is not thread safe, it would be unusable otherwise.
Naming I prefer
newXxxx
or createXxxx
create a new instance every time. getXxxx
gives you an instance if it already exists but won't create one. acquireXxxx
or valueOf
create one as needed, may or may not be new. In this case it is like Calendar.getInstance()
which creates a new instance each time.
Example:-
ClassA a = new ClassA(NumberFormat.getInstance(Locale.GERMAN));
Normal Use of NumberFormat :
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); nf.setMinimumFractionDigits(2); nf.setMinimumIntegerDigits(1); nf.setGroupingUsed(true); java.lang.Number num = nf.parse(Preis);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.