It’s been a while since I’ve been bitten by a multi-threading issues with the code that we produced, but this one is probably very common problem that is hidden until it’s too late. When using SimpleDateFormat, one needs to remember that it is not thread safe class: so if you have an instance of it that is shared across threads (for example static final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
, you need to synchronize access to it. There are several ways to do it. The easiest is to use “synchronized” when accessing the methods for parsing and formatting, but you might pay a hefty performance penalty for doing that. If you are only interested in formatting, you can use FastDateFormat.html class. Or you can create a ThreadLocal, and initialize your format in initialValue
method.