Nice to @Share?

Joshua Bloch jjb at google.com
Mon Feb 22 12:38:17 PST 2010


Some say it's nice to @Share, but not me. Draft 0.1.5 of the Project Lambda
spec contains some discussion of an @Shared annotation to "allow unqualified
references to upplevel variables (all sorts) if they are marked @Shared."
 There are several reasons that I believe this not a good idea:

(1) For fields (instance or static) this annotation is not required today
(in anonymouns class instance creation expressions), and I believe that
programmers are likely to see it as an added annoyance (like the current
situation with final variables).

(2) For local variables, I see it as too much magic:

    @Shared int i;

 has a totally different implementation from:

    int i;

The latter creates a "container object" on the heap, the former doesn't. The
semantics (in particular, the lifetime) and the performance are likely to
differ significantly.

(3) I believe it's an abuse of annotations.  Some may liken it to @Override,
but I believe this is specious. The @Override annotation merely expresses a
compile-time assertion that the compiler is able to verify. The proposed
@Shared annotation changes the semantics of the language.

(4) If, in spite of all the above, it is the consesnsus that such an
annotation is still a good idea, I believe the name @Shared could hardly be
more misleading. In practical terms, it means "this variable must *not* be
shared (without additional synchronization)." It would typically be used
when the programmer could assert that the variable in question would never
be sharead among multiple threads.

            Josh


More information about the lambda-dev mailing list