Tuesday, April 18, 2006

Java DateFormat is not threadsafe

Java DateFormat and SimpleDate classes are not threadsafe.

When an application has a few common date formats it seems natural to have them in some common place like static variables or in some kind of singleton.

However as per this bug report last updated in 2001, date format is not thread safe :-


Also the sun java doc for 1.4 and 1.5 confirms the same :-



Date formats are 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.

What does that impact ?

Well if the methods of dateformat do not use instance variables like most servlets, i guess we should be ok, even if multiple threads access the dateformat, just like servlets.

However since the javadoc "recommends to create separate format instances for each thread" we might use thread local variables to store the DateFormats. That way instead of creating a new DateFormat each time it is needed, we will get only as many DateFormats as there are threads using them.


Blogger Li Ma said...

I created a thread-safe Date Fomatter and Parser in Java.
It maintains only one instance of SimpleDateFormat for each thread and each format pattern.

Please check my blog to see source code:


Hope it can be helpful.

4:39 PM  
Anonymous Anonymous said...

Don't use the code menthioned by Li!!

Instead use joda time. It's fast and thread safe. It will also be added to java 7 making your code ready for the future.

4:11 AM  

Post a Comment

<< Home