Synchronization
Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally
The above line is mentioned in the JavaDoc of SimpleDateFormat class.
Does it mean that we should not create the SimpleDateFormat objects as Static.
And If we create it as static, so wherever we are using this object we need to keep it in Synchronised Block.
If multiple threads access a format concurrently, it must be synchronized externally . To make the SimpleDateFormat class thread-safe, look at the following approaches : Create a new SimpleDateFormat instance each time you need to use one. Although this is thread safe, it is the slowest possible approach.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.
Not thread safe − java. util. Date is not thread safe, thus developers have to deal with concurrency issue while using date. The new date-time API is immutable and does not have setter methods.
Yes SimpleDateFormat is not thread safe and it is also recommended when you are parsing date it should access in synchronized manner.
public Date convertStringToDate(String dateString) throws ParseException {
Date result;
synchronized(df) {
result = df.parse(dateString);
}
return result;
}
one other way is on http://code.google.com/p/safe-simple-date-format/downloads/list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With