@GuardedBy annotation with java.util.concurrent.locks.ReadWriteLock

Greg Mattes picture Greg Mattes · Oct 19, 2011 · Viewed 32.7k times · Source

What is a proper/preferred way to annotate fields that are protected with a ReadWriteLock so that tools like FindBugs can leverage the annotation? Should the name of the ReadWriteLock simply be written in the @GuardedBy annotation. Is there ever a reason to write the name of just the read lock, or just the write lock, in the @GuardedBy annotation? Does FindBugs, or other tools, even support ReadWriteLock in @GuardedBy?

Answer

Michael Deardeuff picture Michael Deardeuff · Nov 13, 2011

At the time of this writing, @GuardedBy isn't fully implemented by Findbugs, and is mostly just for documentation. (It is partially implemented.)

I always use @GuardedBy("readwritelock") or the object that I use to synchronize.

For example of the latter:

class Example {
    private Object lock = new Object();

    @GuardedBy("lock")
    private Stuff innards = ...;

    public void work() {
        synchronized(lock) {
            workWith(innards.goop());
        }
    }        
}