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.