Tuesday, February 24, 2009

The joys of FindBugs

Ladies and Gentlemen, I am writing to you today to speak on the joys of FindBugs. FindBugs (http://findbugs.sourceforge.net/, Eclipse update site http://findbugs.cs.umd.edu/eclipse), for the uninitiated, is a static code analysis tool, which is quite good at performing as its name might lead you to believe.

Similar to other static code analysis tools (e.g. PMD), it has a number of categories of various code issues, ranging from dodgy practices and bad form, to downright errors (null pointer deferences, anyone?). I wholeheartedly recommend running it on your code on a regular basis, and want to present below one example recently of where it helped me.

See anything wrong with the following?

new Thread( new Runnable(){
public void run() {
// long running code in a separate thread... or is it?

This defect was sprinkled in various places throughout our 650+ class codebase. FindBugs quickly found the issue, providing the following helpful advice:

M M Ru] Invokes run on a thread (did you mean to start it instead?) [RU_INVOKE_RUN]

This method explicitly invokes run() on an object. In general, classes implement the Runnable interface because they are going to have their run() method invoked in a new thread, in which case Thread.start() is the right method to call.

Think of FindBugs as your fine-toothed comb; it instantly spotted a number of places in our application where we thought we were dumping long-running processes into separate threads, but in actualality were simply running them in the same.