A nasty surprise

This has been mentioned before, but something good to note: Java’s SimpleDateFormat is not thread-safe. We recently ran into an issue where we were getting absolutely bizarre dates and unreproduceable exceptions, and it turned out that the culprit was a static SimpleDateFormat object that was being shared among four threads. Every so often we were basically lucky enough to get an exception, though it makes me uncomfortable to think about what was parsed incorrectly and logged in the database. Obviously we had to re-run everything once we had synchronized the code that accessed the static SimpleDateFormat.

This highlights another danger of threading: it sometimes doesn’t matter how carefully you protect your own code, because you may occasionally (frequently) run into libraries that aren’t threadsafe- even ones from major players like Sun/Oracle (who at least note it in the docs, but that makes me wonder- why didn’t they just fix it so that there were synchronized options?). It also drives home the need for copy constructors and minimizing shared data- static objects being prime examples- if you make even a rudimentary attempt at handling threads yourself.

Or you could just use a functional programming language. I’m beginning to see the appeal, to be honest- I would rather have methods who return copies of their object instead of methods that affect their instance in-place. Maybe it’s time to start considering Scala?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s