DateFormat and Static analysis

April 24, 2008

Just yesterday, at work, I caught more code using java.util.DateFormat in a non-safe way, so today I looked through old mail and the like trying to find one of the better summaries of the DateFormat situation I’d read. I found this one :

http://blogs.atlassian.com/developer/2007/07/dateformat_objects_and_threads.html

I mentions the non thread-safety of the DateFormat class (something that ought to be well known by now!), and lightly discusses ideas for working around the problem.

What’s missing from the post above, however, is any discussion of how developers might find and correct all of their existing DateFormat usage after learning about this problem, and how they might prevent further incorrect usage in the future.

This is where static analysis comes in. PMD, a popular Java-language static analysis tool, already has a rule relating to thread-safe DateFormat usage. This page :

http://pmd.sourceforge.net/rules/index.html

mentions the below rule :

UnsynchronizedStaticDateFormatter: SimpleDateFormat is not synchronized. Sun recommends separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized either on method or block level.

This rule likely would have caught the above mentioned problem at Atlassian, and certainly would have prevented the similar problem in my company’s code (I checked).

Overall, I’m surprised to see development teams doing very little with static analysis, as there is quite a bit of low-hanging-fruit to be gained from tools such as PMD and FindBugs.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: