One reason for having a weblog is that it makes a handy notebook of important things to remember. For instance, I cut-and-paste from this post on reconfiguring log4j every few months.
So, to help my memory, I now committing to the Interweb the fact that DateFormat is not thread-safe, and neither is SimpleDateFormat, and I'm not the first to do so.
Now, excuse me while I code a small patch for a production application...
Comments
It is an easy thing to overlook. I just wish I understood why they didn't make it thread safe. Seems to me that it is the sort of thing you would expect to be threadsafe.
There was a good article in Dr Dobbs about this, some potential fixes, and how well they work. The best approach was to use thread locals over synchronized methods.
Here is a thread safe wrapper:
http://www.jsourcery.com/output/apache/james/2.20/org/apache/james/util/SynchronizedDateFormat.html
I know there is a least one more OSS library that has a threadsafe wrapper implementation of DateFormat.
It IS reported as a bug:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4228335
But, the JavaDoc does warn about thread issues. RTFM.
FastDateFormat from commons-lang, thread-safe and built for speed.
Nice find, Jed. Unfortunately, FastDateFormat only formats dates, it doesn't parse them.