gimbal2 wrote:If you use the same SimpleDateFormat for formatting in multiple threads, you get output like this (4-digit year, 3-digit day-of-year, 2-digit hour [0-23], 2-digit minute, underscore, numeric count) [this is real output from our system, not a contrived example]:
I wonder what might go wrong when multiple threads use the same formatter? They seem pretty stateless to me once you construct them.
user1980584 wrote:it depends on the instance in question. if an instance of the object is only used by a single thread, then, yes, using an instance variable will work just fine.
I read up about ThreadLocal and am a bit confused. What it does is essentially give each thread it's own local variable, correct? If that is the case, then how does it differ from just creating an instance variable? Does it give any memory or performance benefits?
gimbal2 wrote:That's a shame. this issue came to light a long time ago and is definitely not one of those "theoretical" problems. plenty of people have run into this for real (myself included).
This thread really surprises me, in a bad way. I have stuck formatters in statics for webapps without running into the mentioned issues... but now i am definitely going to experiment.
On the other hand for years now i have stopped being scared of creating objects so nowadays i dont reuse formatters anymore. This just strengthens my beliefs :)that is definitely a good place to be, in general. that said, formatters like SimpleDateFormat are not necessarily cheap. they have to parse the given String format each time you create them. if you do a lot of date/time formatting, this could be an issue. obviously, the lesson here is "default to safe" and if you have performance issues, and profiling indicates the formatters as the problem, then (and only then) look into ways to start caching formatters.