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

Michael Hixson michael.hixson at gmail.com
Wed Jul 5 23:59:52 EDT 2017


AtomicReference and VarHandle are specified to use == in compareAndSet
(and related) operations [1].  Using == to compare instances of
value-based classes may lead to "unpredictable results" [2].  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>>?

-Michael

[1] http://download.java.net/java/jdk9/docs/api/java/util/concurrent/atomic/AtomicReference.html#compareAndSet-V-V-
[2] http://download.java.net/java/jdk9/docs/api/java/lang/doc-files/ValueBased.html


More information about the Concurrency-interest mailing list