[concurrency-interest] JCIP annotations: @GuardedBy

Philip Aston philipa at mail.com
Sat Apr 5 10:08:19 EDT 2014

Does anyone use the JCIP annotations? What's your take on the following?

We use the Java Concurrency In Practice annotations. This is mostly a
documentation discipline, but it also helps findbugs
<http://findbugs.sourceforge.net/manual/annotations.html> tell us not to
be stupid.

The class level @Immutable / @ThreadSafe / @NotThreadSafe are useful and
self explanatory.

Unfortunately, interpreted strictly according to JCIP Appendix A,
@GuardedBy is less so. It is not expressive enough to cover common
locking patterns. E.g. this might look right to the casual eye:

class Foo {
  final Collection bah = new ArrayList();

but @GuardedBy refers to the field bah, which is final so doesn't need a
guard. There's no way to indicate access to the collection itself should
be guarded - e.g. that you must hold the lock on bah before iterating
over the collection.

The JCIP book ignores this distinction. E.g. Listing 11.6, page 236. I
find this a rare flaw in an otherwise very precise book. That "its
obvious what was intended" is a poor defence since the whole point of
the annotations is to specify intent.

Maybe Java 8 / JSR 308 is the answer and I should write something like:

    @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE_USE })
    public @interface GuardedBy2 {
        String value();

    final Collection bah = new @GuardedBy2("self") ArrayList();

but I'm on Java7, so

    final Collection bah = new /* GuardedBy("self") */ ArrayList();

for now.


- Phil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20140405/cba63dfa/attachment.html>

More information about the Concurrency-interest mailing list