Can we declare SimpleDateFormat objects as static objects
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?
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
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);
DateFormat is not thread-safe. If multiple threads use the same DateFormat object without any synchronization you can get unexpected results. So you should either synchronize access to the DateFormat object, use a ThreadLocal variable or use an alternative Date API such as Joda-Time.
For more information on how to do this, take a look at this blog post: DateFormat with Multiple Threads
An alternative if you are already using Apache Commons:
static shouldn’t be a problem.
Since AFAIK no guarantees are made about thread safety you’d have to check the source code for that. And even if you come to the conclusion that it is thread safe, this might change with the next release. As said in another answer they are not thread safe.
Do you really allocate such a huge amount of threads that giving each thread its own Format is a problem?
- Database Administration Tutorials
- Programming Tutorials & IT News
- Linux & DevOps World
- Ebook Reviews
- PES Matches, Skills & News