Be careful with SimpleDateFormat

Torbjørn Kristoffersen
1 min readAug 5, 2015

--

Be careful with SimpleDateFormat in Java. I’ve burned myself like this. It can cause Heisenbugs if you are really unlucky.

Intuitively, by looking at the name and the functionality provided by SimpleDateFormat, it’s almost a given that it’s thread-safe. But it’s not.

private static final DateFormat df = new 
SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Say you share a static instance of a SimpleDateFormat between multiple threads (e.g. on an application server), most of the time it’ll work, but occasionally you can actually get corrupted dates e.g. dates hundreds of years ahead in time.

These are the most common solutions:

  1. Slap a synchronized on the df object above. E.g.
synchronized(df) {
df.parse(stringToBeParsed);
}

2. Roll your own date formatter using String.split and building a Date object using Calendar.

3. Use FastDateFormat in Apache Commons.

4. Use the Joda time library

5. In Java 8 they released DateTimeFormatter and it’s thread-safe. However some of us are still “stuck” on Java 7 so it wasn’t an option for me.

What I would not recommend is ThreadLocal to provide a singleton instance of SimpleDateFormat per thread in your app server. I’ve seen some odd results from this and you can also end up with a memory leak.

--

--