FindBugs; fix bugs


This weekend, I came across FindBugs, an interesting application that analyzes Java programs for potential bugs.  It was created by William Pugh at the University of Maryland, who is a four-time JavaOne Rock Star.  Google, for example,  has used his tool for finding problems in their Java code.

FindBugs made plenty of suggestions for some code I’ve been working on, and some of them looked like things that I should fix.  I found one thing in particular of interest.  I’ve been using the following pattern for the lazy instantiation of singletons:

class Foo {
    private Helper helper = null;
    public Helper getHelper() {
        if (helper == null)
            synchronized(this) {
                if (helper == null)
                    helper = new Helper();
        return helper;

This article explains that that approach doesn’t work because instruction reordering in the compiler may cause the helper variable to be non-null in a thread that didn’t create the object but the Helper instance to be not yet initialized. It goes on to explain that for static variables one can get around this problem by using a separate class.

class HelperSingleton {
    static Helper singleton = new Helper();

Without any synchronization, the class loader makes sure that the singleton variable will be fully initialized before any other thread can access it.  Also, the class loader won’t load this second class before it is needed.

Anyway, this finding alone should get Java programmers interested in trying out FindBugs in their applications. For more information, take a look at the talk William gave at JavaOne last year.

1 Comment

  1. [...] This post was mentioned on Twitter by Gene Golovchinsky. Gene Golovchinsky said: Posted "FindBugs; fix bugs" by Andreas Girgensohn #java [...]

Comments are closed.