Question:
Is SimpleDateFormat threadsafe? I am trying to
track down a bug where a date formatted "yyyy-MM-dd" actually came out
as 2000-06-0001. I have four threads accessing the format method of
my date formatter class at approximately the same time.
Answer:
SimpleDateFormat is not threadsafe. The general rule to follow is
that if the API documentation does not state that a class or method is
threadsafe, then you must assume it isn't. Whenever you share
resources between threads, you should protect those resources with
synchronized blocks if you are unsure as to whether or not they
already protect themselves. When it comes to the core APIs, you
can always look at the Java source code that comes with the JDK to
verify. However, just because the source is thread safe does not
mean that the class is required to be thread safe. Unfortunately,
the Java Platform specification process is not so rigorous as to tell
you how each and every standard class is supposed to behave, forcing you
to rely on the javadocs as an ill-substitute for a more formal
specification.