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 :-

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4228335

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

http://java.sun.com/j2se/1.4.2/docs/api/java/text/DateFormat.html
http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html

Synchronization

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.

2 Comments:

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:

http://li-ma.blogspot.com

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