Why is Java's SimpleDateFormat not thread-safe?

Vivek Sharma picture Vivek Sharma · Jul 27, 2011 · Viewed 150k times · Source

Please tell with a code example why is SimpleDateFormat not threadsafe. What is the problem in this class? Is The problem with format function of SimpleDateFormat? Please give a code which demonstrates this fault in class.

FastDateFormat is threadsafe. Why? what is the difference b/w the SimpleDateFormat and FastDateFormat?

Please explain with a code which demonstrates this issue?

Answer

Bozho picture Bozho · Jul 27, 2011

SimpleDateFormat stores intermediate results in instance fields. So if one instance is used by two threads they can mess each other's results.

Looking at the source code reveals that there is a Calendar instance field, which is used by operations on DateFormat / SimpleDateFormat.

For example parse(..) calls calendar.clear() initially and then calendar.add(..). If another thread invokes parse(..) before the completion of the first invocation, it will clear the calendar, but the other invocation will expect it to be populated with intermediate results of the calculation.

One way to reuse date formats without trading thread-safety is to put them in a ThreadLocal - some libraries do that. That's if you need to use the same format multiple times within one thread. But in case you are using a servlet container (that has a thread pool), remember to clean the thread-local after you finish.

To be honest, I don't understand why they need the instance field, but that's the way it is. You can also use joda-time DateTimeFormat which is threadsafe.