SimpleDateFormat in Java is not Thread-Safe Use Carefully (original) (raw)
SimpleDateFormat in Java is a very common class and often used to format Date to String and parse String into Date in Java, especially in pre Java 8 world, but it can cause very subtle and hard to debug issues if not used carefully because both DateFormat and SimpleDateFormat both are not thread-safe and buggy. A call to format() and parse() method mutate the state of DateFormat class and should be synchronized externally in order to avoid any issue but many Java developers are not aware of these. That's why it's better to completely avoid using SimpleDateFormat class especially if you are using Java Se 8 or higher version like Java SE 11 or Java SE 17. here are a few points which you should take care while using SimpleDateFormat in Java:
SimpleDateFormat in Java is not Thread-Safe
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.
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 the state of DateFormat object and can create subtle and hard to fix bugs while formatting Strings or creating dates in Java. The best is to avoid sharing of DateFormat class altogether.
If you have the option use the JODA date time library for your date and time-related operation. it's easy to understand and portable with Java Date API and solves all thread-safety issues associated with SimpleDateFormat in Java.
Another good alternative of SimpleDateFormat in Java is Apaches' commons.lang package which holds a class called FastDateFormat utility class and thread-safe alternative of SimpleDateFormat in Java.
Another approach of synchronizing DateFormat and SimpleDateFormat is using ThreadLocal, which creates SimpleDateFormat on a per Thread basis but it can be a source of severe memory leak and java.lang.OutOfMemoryError if not used carefully. so avoid until you don't have any other option.
And, if you like a list, here are 10 reasons why you should not be using SimpleDateFormat class in Java anymore, especially after Java SE 8 release:
That’s all on SimpleDateFormat in Java. Many people have pointed out flaws in the design of the Format class but unfortunately, Sun or Oracle has not addressed them in any release not even in JDK7. SimpleDateFormat is still the first choice because of its availability on standard libraries but should be used carefully.
Other Java tutorials you may like
P. S. - Things have changed from Java 8 onwards and you have a better Date and Time API with new classes for everything related to date and time, including formatting. If you are running on Java 8 or higher version then you should use DateTimeFormatter class to format the Date String in Java. They are both Immutable and Thread-safe.