Java

SimpleDateFormat + Calendar = thread unsafe

Posted

http://javarevisited.blogspot.com/2012/03/simpledateformat-in-java-is-not-thread.html

1) Use local DateFormat or SimpleDateFormat objects for converting or formatting dates in Java. Making them local ensure that they will not be shared between multiple Threads.

2) If you are sharing Date for SimpleDateFormat class in Java then you need to externally synchronize

call to format() and parse() method as they mutate state of DateFormat object and can create subtle and hard

to fix bugs while formatting Strings or creating dates in Java. Best is to avoid sharing of DateFormat class altogether.

3) If you have option use JODA date time library for your date and time related operation. its easy to understand and portable with Java Date API and solves all thread-safety issues associated with SimpleDateFormat in Java.

4) Another good alternative of SimpleDateFormat in Java is Apaches’ commons.lang package which hold a class called  FastDateFormat utility class and thread-safe alternative of SimpleDateFormat in Java.

5) Another approach of synchronizing DateFormat and SimpleDateFormat is using ThreadLocal, which create SimpleDateFormat on per Thread basis but it can be source of severe memory leak and java.lang.OutOfMemoryError if not used carefully. so avoid until you don’t have any other option.
Read more: http://javarevisited.blogspot.com/2012/03/simpledateformat-in-java-is-not-thread.html#ixzz20mMmGbc5