Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Synchronization issue with NumberFormat?

Tags:

I use java.text.NumberFormat simply to convert numbers into more readable Strings, with commas separating thousands, etc. Basically I define it as:

public static NumberFormat nf = NumberFormat.getInstance(Locale.US); 

...and then I just call nf.format(some_number) in any thread where I want to make a readable version of a number. But looking at the JavaDoc, it says: "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."

If I am only using the format(number) method of the NumberFormat object, could there ever be a synchronization issue? I tried using NumberFormat.getInstance(Locale.US).format(number) instead, but there is overhead associated with doing that every time that I feel is probably not really needed. Does this really need external synchronization? Or is there a simpler, efficient way of accomplishing the same thing without NumberFormat?

Thanks!

like image 772
DivideByHero Avatar asked Aug 16 '09 20:08

DivideByHero


2 Answers

Even if format is the only method you ever call, it's still not thread-safe. In fact, we've had bugs at work due to this. We usually either create NumberFormat objects on the fly, or use a ThreadLocal as Gerco suggested. If you wanted to get fancy, you could subclass NumberFormat and in the format method, either synchronize before calling format on a delegate NumberFormat or use a ThreadLocal to retrieve a delegate.

However, I believe the most straightforward way, especially if you're going to format/parse several numbers in a row, is to use a ThreadLocal manually.

like image 84
Adam Crume Avatar answered Sep 23 '22 12:09

Adam Crume


Use a ThreadLocal<NumberFormat>. That way each thread will have it's own private NumberFormat instance and there will be no need to synchronise and only minimal overhead.

like image 40
Gerco Dries Avatar answered Sep 25 '22 12:09

Gerco Dries