Some time ago I had to fix a really strange bug in a Java web application. A date displayed to the user was going crazy. Where it should be 20 November 2011 it was something like 12 January 510 or 4 October 3040. The app was obviously broken...
I checked the code and at first it looked all right. There was an utility class looking something like that:
I debugged the code and it run OK. I googled a few times and nobody seemed to had this problem. So I went back and forth between source files wondering how this was possible... and then I got an idea. I wrote a small program to prove me right and it all became clear. The program looked like that:
And the results were:
As you can see the SimpleDateFormat class is not thread-safe. There is even a caution in the Oracle JavaDoc.
Solution
The simplest solution is to create a new SimpleDateFormat object every time it is needed. However, according to this source the fastest way to use DateFormat in a multi-threaded environment is to use ThreadLocal. So, our utility class could look like this:
Summary
To sum up, if your application works in a concurrent environment, you should always check your classes for thread-safety, especially when using Java Formatters.