[concurrency-interest] Should I avoid compareAndSet with value-based classes?

Andrew Haley aph at redhat.com
Fri Jul 7 04:39:13 EDT 2017

On 06/07/17 17:33, Gil Tene wrote:

> We could further discuss whether or not the JVM is allowed to
> "falsely" indicate that == is true (or that != is false) even when
> the instances differ in value (so are not .equals()). It is.

No it isn't, unless you believe that the paragraph on value-based
classes overrides the JLS.  For it to do so, the definition of
reference equality would have to change.  Right now, all it says is
"At run time, the result of == is true if the operand values are both
null or both refer to the same object or array; otherwise, the result
is false."  I suppose you could argue that in the context of a
value-based class the notion of "same object" is vacuous, but that
would be a heck of a stretch.

> Doing that may certainly surprise anyone who uses the identity based
> == for anything to do with instances of value-based classes, even
> tho using it would be silly given that == might obviously be
> always-false. For example, I could see how someone may mistakenly
> try to use == as an "optimization" on the assumption that if they
> get lucky and == is true, .equals() must be true as well, and that
> evaluating == might be cheaper, but they would still "do the right
> thing" in the != case. But that would be a mistake, and a clear
> violation of the "don't do that" admonition above.

Frankly, I don't believe it.  Any JVM which did what you suggest would
IMO be in violation of the JLS and the JVM specification.  It is
possible that the definition of reference equality will be changed, but
that would require the incompatible specification change to be

Andrew Haley
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671

More information about the Concurrency-interest mailing list