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

David Lloyd david.lloyd at redhat.com
Thu Jul 6 13:46:45 EDT 2017

I sent this from the wrong e-mail address due to MUA change.  Resending...

On Wed, Jul 5, 2017 at 11:20 PM, Gil Tene <gil at azul.com> wrote:
> 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.

How many generic concurrent data structures exist which (to name one
example) use compareAndSet() to update a value in the two-argument
replace() case?  What measures do (or can) these structures take to
prevent these magical value types from being used in these cases?

If we (as the collective concurrency community and as the greater Java
community) allow these magical value types to *actually* stop working
in some logical fashion with == and therefore with CAS, we are utterly
deserving of the chaos that will result.  In particular, it would be a
terrible idea to allow the basic CAS loop to be broken for some Object

   do {
       a = atomic.get();
       b = compute(a);
   } while (! atomic.compareAndSet(a, b));

No amount of performance optimization is worth breaking the
correctness of this fundamental structure.

More information about the Concurrency-interest mailing list