Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we declare SimpleDateFormat objects as static objects

Tags:

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?

like image 794
Joe Avatar asked May 26 '11 11:05

Joe


People also ask

Should DateTimeFormatter be static?

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).

How do I declare SimpleDateFormat?

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.

Is SimpleDateFormat can be used in multithreaded environment?

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.

What is the difference between DateTimeFormatter and SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.


2 Answers

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.

like image 70
jmj Avatar answered Oct 20 '22 23:10

jmj


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); 
like image 22
Magnilex Avatar answered Oct 21 '22 00:10

Magnilex