If you actually do try to use a SimpleDateFormat by multiple threads at the same time, it will throw exceptions at you that may include but are not limited to (paraphrasing here):
exception for input string ""
multiple decimal places are not allowed
value E4.234E (random value, but usually includes the letter E) is not a number
The date may be completely incorrect ( I got between 1AD and 4700 AD today ), plus one that had a year of 20100201. Surprisingly, the month, day, and time were usually correct though.
I guess I will be thinking twice before declaring my date formatter object as a class-level field in the future.
Everything is theoretically impossible, until it is done. ~Robert A. Heinlein
Yes, it is indeed not thread-safe. The API documentation of SimpleDateFormat mentions this:
API documentation wrote:Synchronization
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.
If you don't want to create a new SimpleDateFormat object every time you need it, you can wrap it in a ThreadLocal. That will automatically create a new SimpleDateFormat object for each thread that uses it.
This is interesting information. Question: I created a simple utility class when I found myself creating redundant code. It looks like this.
I know that synchronizing an entire method is usually a bad idea, but since these are very small, static methods, it seemed like an efficient way to do it. But maybe this is all wrong. Should I be using ThreadLocal like your example instead of synchronizing like this?
"The good news about computers is that they do what you tell them to do. The bad news is that they do what you tell them to do." -- Ted Nelson
The synchronization in your example is unnecessary, because the SimpleDateFormat objects in your code are local variables - you're creating a new SimpleDateFormat object each time the method is called. Synchronization would only be necessary if you use the same SimpleDateFormat object from multiple threads at the same time, as Tina was doing. You could just remove the synchronized in your code and it would work just as well.
Suppose your code looked like this:
then you would need the synchronization - because there's only one SimpleDateFormat object that's shared by all threads calling the getTodayYYYYMMDD() method.
Ofcourse, the disadvantage of synchronization is that it's a bottleneck - only one thread at a time can be executing the method, other threads have to wait.
To avoid this bottleneck, and also avoid creating a new SimpleDateFormat each time you call the method, you can use the ThreadLocal as I showed. This will make sure that for each thread that calls the method there is a separate instance of the SimpleDateFormat object - but it won't create it every time the method is called.