Middle · Trace · CAS publication compares reference identity

Explain the successful first publication and the failed value-equal expected reference.

Think through your answer before opening the explanation.

Runtime & concurrency

using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Reflection;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

State current = new(0);
State original = current;
State candidate = new(1);
bool first = ReferenceEquals(Interlocked.CompareExchange(ref current, candidate, original), original);
State lookalike = new(1);
bool sameValue = current == lookalike;
bool matched = ReferenceEquals(Interlocked.CompareExchange(ref current, new State(2), lookalike), lookalike);
Console.WriteLine($"published:{first}");
Console.WriteLine($"value-equal:{sameValue}");
Console.WriteLine($"reference-match:{matched}");
Console.WriteLine($"current:{current.Count}");
sealed record State(int Count);
Reveal answer and reasoning

The lines are published:True, value-equal:True, reference-match:False, and current:1. The first CAS receives the actual original zero-state reference and replaces it with the candidate containing one. The new lookalike also contains one, so record equality is true. It is nevertheless a different reference, and using it as the expected CAS value does not match current, so the attempted replacement with two fails.

The stored state therefore remains the first candidate with count one. A common wrong trace publishes two because it assumes the overloaded equality operator controls Interlocked's reference comparison. This snippet exercises real failed matching deterministically without any OS scheduling. The external workers test a separate bounded retry protocol; their candidate-attempt count may vary and is not another fixed line in this output.

Neither example grants an external delivery guarantee simply because a local publication or notice counter succeeded.

What a strong answer covers

  • The exact original reference enables the first exchange.
  • A value-equal lookalike still fails identity matching.
  • Current remains one after the failed attempt.

Common pitfall

Assuming record value equality changes the identity comparison performed by reference CAS.

Follow-up questions

  1. What if the actual current reference is supplied instead?
  2. Why would comparing returned records with == be unsafe as a success test?

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