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.
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.
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 🙂 .
Added information to Java 8.