SimpleDateFormat monthFormat = new SimpleDateFormat("MMMM"); SimpleDateFormat fullFormat = new SimpleDateFormat("EE MMM dd, HH:mm:ss")
I have several such piece of code which gets invoked often, would it make sense to declare them as static
variables?
Is it thread safe to pass dynamic arguments to the format()
method in such cases?
DateTimeFormatter itself has numerous static constants like this. It is even recommended to store the (immutable) formatter in a static constant (for performance reasons because constructing a formatter can be quite expensive).
Creating a SimpleDateFormat You create a SimpleDateFormat instance like this: String pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); The pattern parameter passed to the SimpleDateFormat constructor is the pattern to use for parsing and formatting of dates.
Java's SimpleDateFormat is not thread-safe, Use carefully in multi-threaded environments. SimpleDateFormat is used to format and parse dates in Java. You can create an instance of SimpleDateFormat with a date-time pattern like yyyy-MM-dd HH:mm:ss , and then use that instance to format and parse dates to/from string.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
No they aren't thread-safe.Use Joda-time's version instead.
Or make them wrapped in synchronized method and make it thread-safe
Doc Says it clearly
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.
As of Java 8, this is supported in the new Date API. DateTimeFormatter
is thread-safe and can do the same work as SimpleDateFormat
. Cited from the JavaDoc:
A formatter created from a pattern can be used as many times as necessary, it is immutable and is thread-safe.
To be extra clear, it is perfectly fine to define a format such as:
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
And use it in methods that can be accessed by several threads concurrently:
String text = date.toString(formatter); LocalDate date = LocalDate.parse(text, formatter);
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