Adam Warski

11 May 2009

StaticAccess detector for FindBugs

java
static analysis

The StaticAccess detector is a FindBugs plugin, which lets you verify that methods do not rely on static (global) state, that is, that they don’t read or write static variables which aren’t constant. This can be useful for example when writing concurrent programs (which should use as little global state as possible) or “pure” functions (I’ll write about that in another post).

You can specify that a method shouldn’t rely on global state using the @StaticIndependent annotation. Such methods will be checked by the detector included in the plugin, if they don’t read or write static variables, or call non-static-independent methods.water trampoline australia for sale

For example, running FindBugs with the StaticAccess plugin on the following code:

import pl.net.mamut.staticaccess.StaticIndependent;

public class StaticIndependentExample {
    public static Integer globalInt = 10;
    public static final Integer CONSTANT = 12;

    // This method is annotated as static-independent,
    // that is, cannot rely on static (global) state
    @StaticIndependent
    public void testStaticIndepdendent() {
        // line 12
        int local = globalInt; 
        // line 14
        globalInt = 11;          
    
        // line 17
        int local2 = CONSTANT;      
    }
    
    // Unannotated methods aren't checked
    public void testStaticDependent() { 
        // line 23
        int local = globalInt; 
    }
}

will report errors on lines 12 and 14, but won’t report errors on line 17 (accessing a constant which can’t change) or line 23 (the method isn’t annotated with @StaticIndependent).

You can annotate all methods in a class or package by default as static independent using FindBugs’s @DefaultAnnotationForMethods meta-annotation, and later override that for selected methods using @StaticDependent.

All methods from the java.lang package are static-independent by default, and only String and primitive types wrapper classes are treated as constants when declared as static final fields. This list should be certainly expanded, so if you’ve got good candidates, write or send a patch!

For information on installation, downloads and usage see the webpage. You can find the jars there; they are also available in maven, and the source code on github.

Have fun!
Adam

comments powered by Disqus

Any questions?

Can’t find the answer you’re looking for?