LendKey

Thursday, October 18, 2007

A Thread Safe Date Formatter/Parser

I have seen many different ways to use DateFormat classes(most ly SimpleDateFormat) from different people including myself, and unfortunately, most of them are either buggy or not efficient.
The following are the most common scenarios I saw:
1. Use a static final formatter in different thread:
static final private DateFormat df = new SimpleDateFormat("yyyy/MM/ddd");
...
void myMethod()
{
df.parse(..)
df.format(..)
}
People, including me, were thinking to reduce number of instances of df and reuse it everywhere. But this is dead wrong! The JavaDoc has clearly mentioned that SimpleDateFormat is NOT thread-safe. So once you put multiple threads using the same instance, strange result will happen. Most of the time, people tent to ignore the warning from JavaDoc or don't even know it. And most of time, the code works ok, because after all, there is not that many threads running in parallel if you are only doing a small website.
2. Create DateFormat instance eveyrtime it is used
void myMethod()
{
DateFormat df= new SimpleDateFormat("yyyy/MM/dd");
df.parse(..);
df.format(..);
}
This works without bug, but you can tell lots of df objects will be created, they I always feel it is not good to create extra objects when you are coding for large and heavily loaded website.
3. Apache Jakarta Common Lang's FastDateFormat
http://www.jdocs.com/lang/2.1/org/apache/commons/lang/time/FastDateFormat.html
This is a thread-safe solution. But the problem is still you have to create each instance for different pattern. Many times in your code, you have to create multiple instance of the same pattern at many different places, which mean multiple different objects to do the same thing. The biggest problem with FastDateFormat is it only format and does not do parsing.
So after spending about an hour or so doing research, I came up with my own solution:
ThreadSafeDateParser.
Here's the class:

And the test Class:



Idea of the class is:
  1. Very easy to use. Just call those static methods and provide a string and pattern. The class will handle everything else, including formatter object creation, thread mangement, etc.
  2. For same patter and same thread, the class create only one instance of DateFormat, so you got thread-safe and use the minimum system resource
I tested the class with 1000 threads running at the same time, and it works solid with out any problem.

Hopefully this is something lots of people can reuse in your code.
I know I do not have locale and timezone handling yet. I you have any comment or suggestion, feel free to share.

Enjoy!

Li