首页 > 代码库 > SimpleDateFormat in Java is not Thread-Safe Use Carefully

SimpleDateFormat in Java is not Thread-Safe Use Carefully

SimpleDateFormat in Java  very common and used to format Date to String and parse String into Date in Java but it can cause very subtle and hard to debug issues if not used carefully because DateFormat and SimpleDateFormat both are not thread-safe and buggy. call to format() and parse() method mutate state of DateFormat class and should be synchronized externally in order to avoid any issue. here are few points which you should take care while using SimpleDateFormat in Java:

SimpleDateFormat in Java is not Thread-Safe

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.
 
That’s all on SimpleDateFormat in Java. Many people has pointed out flaw on design of Format class but unfortunately Sun or Oracle has not addressed them in any release not even in JDK7. SimpleDateFormat is still first choice because of its availability on standard library but should be used carefully.



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

SimpleDateFormat in Java is not Thread-Safe Use Carefully