Middle · Explain · CAS publication compares reference identity

Why can value-equal records fail reference CompareExchange, and what belongs outside a retry computation?

Think through your answer before opening the explanation.

Runtime & concurrency

Reveal answer and reasoning

The reference-type CompareExchange overload compares the exact expected reference, not the record's overloaded value equality. A new record containing the same count is a lookalike but not the previously observed object. A retry loop must obtain the actual current reference, derive a valid immutable candidate, and recognize success through the returned reference identity rather than through value equality alone.

Nonrepeatable work must not be performed every time a candidate is computed, since contention can discard that candidate and require another attempt. A local effect after success is still not a durable transaction or exactly-once external delivery. A common wrong answer also assumes CAS automatically prevents ABA; if a protocol republishes an old reference, identity alone does not reveal the intermediate history.

The increasing-count desktop example avoids republishing old states by design, which is a property of that protocol rather than a universal primitive guarantee.

What a strong answer covers

  • Reference CAS does not invoke record equality.
  • Speculative candidate computation must be repeatable.
  • ABA and durable effects need separate protocols.

Common pitfall

Testing CAS success with value equality or doing an irreversible effect on every candidate attempt.

Follow-up questions

  1. How could an old reference reappear?
  2. Why must reachable state remain immutable after publication?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions