SimpleDateFormat considered harmful
There's been some discussion on the lists at work about SimpleDateFormat. Apparently it's not safe to be used by multiple threads simultaneously, despite the fact that theformat()
method doesn't appear to mutate the state of the object. It's a huge design flaw that has bitten many a developer in the ass.The discussion turned to possible workarounds and speculation on their comparative performance. Here's the contenders and my speculation:
- create a new SimpleDateFormat instance on every invocation. I predicted that this approach would be slow because of the computational expense of parsing the format string.
- synchronize() on a single shared SimpleDateFormat instance. I thought this approach would be fastest.
- use some sort of simple pooling mechanism to share multiple SimpleDateFormats between the threads. I figured this approach would be slow because there would be a need for two synchronized() blocks: one for fetching objects from the pool and another for returning them
- Use ThreadLocal, where each Thread has a private SimpleDateFormat instance. I figured this approach would be slow because ThreadLocal probably had some complexity in its implementation.
Well having placed my bets on the synchronized shared instance, I decided to write a bit of code and benchmark the four options. Here's the results, as obtained unscientifically on my Mac Book Pro:
Implementation | Runtime (seconds) |
---|---|
new instance each time | 9.6 |
single synchronized instance | 3.4 |
simple pool | 2.5 |
ThreadLocal | 2.2 |
The results are surprising - ThreadLocal is the clear winner, 50% faster than synchronized(). But don't take my word for it. Critique and tweak SDFPerformance.java and run your own tests.