Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 950
Greg Mattes Avatar asked Oct 19 '11 17:10

Greg Mattes


2 Answers

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());         }     }         } 
like image 115
Michael Deardeuff Avatar answered Sep 18 '22 15:09

Michael Deardeuff


Find bugs supports the following annotations:

net.jcip.annotations.GuardedBy net.jcip.annotations.Immutable net.jcip.annotations.NotThreadSafe net.jcip.annotations.ThreadSafe 

Usage of these GuardedBy annotation should be as follows:

@ThreadSafe   public class Queue<E> implements java.util.Queue<E>   {       private ConcurrentLinkedQueue readWriteLock;        @GuardedBy( value="readWriteLock" )       public boolean offer(E o)       {           return queue.offer( o );      }    }   
like image 31
Mark Avatar answered Sep 18 '22 15:09

Mark