Adding an @Immutable annotation to Java

Brian Goetz brian.goetz at oracle.com
Tue Nov 30 15:29:00 UTC 2021


I don’t see how a restricted reference by itself is useful, if you cannot depend upon the object not being mutated via other references.

Agree; this may help you do local proofs of correctness, and may conceivably help the JIT (though, its pretty smart about figuring this stuff out on its own), but the benefit doesn’t rise to the level of the complexity here.

The main value of an @Immutable designation is that it is safe to share a reference without additional coordination (both sharing with untrusted code, and sharing across threads).  But, this is only useful if the designation is (a) true all the way down, and (b) cannot be subverted by unsafe casts.

One needs look no farther than String to realize the near-hopelessness of this task.  A String is logically immutable, but its representation includes (a) a mutable cache of its hashCode, and (b) a reference to a mutable array of bytes or chars.  Even if we were willing to throw (a) overboard, (b) would require some sort of @TrustMe, which we could conceivably do for jl.String, but couldn’t possibly expose more broadly without driving the value of the mechanism to near-zero.  Treat this as an existence proof that mutability is just too pervasive to contain, at least for now.

There are efforts underway to chip away at some of the untamed mutability; frozen arrays are on the drawing board (addressing (b)), and Valhalla will join records in defining _shallowly_ immutable aggregates.  (It could conceivably go farther, but not until we can at least bring String into the fold.)  But we’d need to make a lot more progress before anyone could consider believing an @Immutable designation.  And if it can’t be believed, it doesn’t have enough value to put in the language.  (No problem with privately using annotations to capture design intent in documentation, but the bar for the language is higher than that.)

There are other impediments too; much ink has been spilled on the challenges of capturing immutability in a type hierarchy as complex as Collections.  But my main point is that while this is something that initially seems desirable, when you start pulling on the string, you realize it is not as useful as it initially seems in an environment of pervasive mutability.




More information about the core-libs-dev mailing list