[concurrency-interest] Should I avoid compareAndSet with value-based classes?
gil at azul.com
Thu Jul 6 00:20:23 EDT 2017
Reference equality for value based classes (as referenced below) lacks meaning, as there is no notion of identity in such classes (only a notion of value). And since compareAndSet on reference fields is basically an idenitity-based operation [in the compare part], the two won't mix well logically.
Specifically, while two references to e.g. java.time.LocalDateTime instances being == to each other *probably* means that the two are actually equal in value, the opposite is not true: Being != to each other does NOT mean that they are logically different. As such, the "compare" part in compareAndSet may falsely fail even when the two instances are logically equal to each other, leaving the rest of your logic potentially exposed.
Bottom line: given the explicit warning to not use == and != on references to value-based instances, I'd avoid using compareAndSet on those references. If you really need to use a value-based class in your logic, consider boxing it in another object that has [normal] identity.
> On Jul 5, 2017, at 8:59 PM, Michael Hixson <michael.hixson at gmail.com> wrote:
> AtomicReference and VarHandle are specified to use == in compareAndSet
> (and related) operations . Using == to compare instances of
> value-based classes may lead to "unpredictable results" . Does
> this mean I should avoid using compareAndSet with arguments that are
> instances of value-based classes?
> It seems like the documentation clearly tells me "yes, avoid doing
> that" but I'm hoping I misunderstood, or maybe AtomicReference and
> VarHandle are exempt somehow. Otherwise, how do I implement
> non-broken compareAndSet and updateAndGet for a java.time.Instant
> value for example? Do I have to box the value in something that's not
> a value-based class first, like AtomicReference<Box<Instant>>?
>  http://download.java.net/java/jdk9/docs/api/java/util/concurrent/atomic/AtomicReference.html#compareAndSet-V-V-
>  http://download.java.net/java/jdk9/docs/api/java/lang/doc-files/ValueBased.html
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
More information about the Concurrency-interest