SimpleDateFormat in multithreaded environment

SimpleDateFormat is wide known in Java as the default tool to convert a String to a (java.util.)Date and vice versa.

Usually you would think you can make a SimpleDateFormat static, like:

private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("ddMMyyyy");

Because we think, that the formatter just contains the formatting rules, which is not the case.

The methods on SimpleDateFormat are not thread safe , because intern it is based on a Calendar attribute, which will be created and modified.

What’s the solution for the problem?
Generally you must either synchronize or always make a new SimpleDateFormat for each conversion.

Other formaters I stumbled across are the multi threaded safe DateTimeFormat of JodaTime or FastDateFormat from apache-commons.

What about an object pool? Well there can be performance gains here (even if they are minimal), but even Joshua Bloch said in his book “Effective Java” not to make pools. Because most JVM implementations are fast enough at reclaiming simple Objects.

Conclusion

Ask yourself. Are you handling with Calendars and Dates often in your application? Then JodaTime surely benefit your overall application. Because it is a far better Time/Date implementation instead of the JVM internal. In Java 8 there will be a new Date/Time inspired by JodaTime.

Do you already have apache-common or do you see many additional benefits in the library for your overall application, than this library may be your choice.

In the end, if you want no additional library, than the only reasonable choice is just to always make a new SimpleDateFormat for every conversion. If you make it synchronize, it work too without a problem, but it may block your throughput and synchronize can always lead to deadlocks and a synchronized block doesn’t look well in the code 🙂 .

Update 5:
Added information to Java 8.

This entry was posted in Formatting, Java, Multi threading and tagged , , , , . Bookmark the permalink.

1 Response to SimpleDateFormat in multithreaded environment

  1. Anonymous says:

    An useful post. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *