Can we declare SimpleDateFormat objects as static objects

Joe picture Joe · May 26, 2011 · Viewed 14k times · Source
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?

Answer

Jigar Joshi picture Jigar Joshi · May 26, 2011

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.