skip to content

How does AtomicReference.compareAndSet compare values, and what goes wrong when you pass it a boxed Integer or a freshly built equal object?

level: middleimportance: should knowfreq 38%

answer

  1. what one atomic step can compare
  2. references versus object contents
  3. autoboxing and the small-value cache
  4. reuse the reference from get()

basics

~20 s

AtomicReference.compareAndSet compares references with ==, never equals(). An equal but different expected object returns false and changes nothing, so a newly built object, or an Integer boxed again outside -128 to 127, can fail silently.

solid answer

~40 s

`AtomicReference.compareAndSet(expected, next)` sets the value only if the current reference `== expected`; it never calls `equals()`. A CAS is one atomic step on one memory location, so it can compare a reference but cannot run arbitrary code over an object's contents. An equal but different object therefore returns `false` and changes nothing, with no exception. Boxing hides this: `Integer` values from -128 to 127 are cached, so `compareAndSet(100, 101)` succeeds, while at default flags `compareAndSet(1000, 1001)` fails because each `1000` is boxed into its own object. A retry loop that re-boxes its expected value then spins forever. Pass the reference you read: `Integer seen = ref.get(); ref.compareAndSet(seen, seen + 1)`, or use `updateAndGet`, which does that for you. For plain numbers, use `AtomicInteger` or `AtomicLong`, which compare primitive values.

code

java · 20 lines
java
import java.util.concurrent.atomic.AtomicReference;

public class CasIdentity {
    record Config(String url) {}

    public static void main(String[] args) {
        AtomicReference<Integer> small = new AtomicReference<>(100);
        System.out.println(small.compareAndSet(100, 101));      // true: both boxes are cached

        AtomicReference<Integer> big = new AtomicReference<>(1000);
        System.out.println(big.compareAndSet(1000, 1001));      // false: two separate boxes

        Integer seen = big.get();
        System.out.println(big.compareAndSet(seen, seen + 1));  // true: the same reference

        AtomicReference<Config> config = new AtomicReference<>(new Config("a"));
        System.out.println(config.get().equals(new Config("a")));                   // true
        System.out.println(config.compareAndSet(new Config("a"), new Config("b"))); // false
    }
}

go deeper

for a junior

Remember that compareAndSet on AtomicReference uses ==, the same identity test you know from comparing two String objects, so an equal but different object does not match and the call returns false.

for a middle

Explain why a CAS compares one reference instead of running equals(), then show the Integer cache making compareAndSet(100, 101) succeed and compareAndSet(1000, 1001) fail at default flags, and the fix of reusing the reference from get().

for a senior

Treat a CAS retry loop that burns a core with no contention as a sign of a re-boxed or rebuilt expected value. In review, look for ignored boolean results, and hold immutable values so a matching reference really means unchanged state.

for a principal

Weigh a team rule that steers boxed numbers away from AtomicReference and toward AtomicInteger and AtomicLong. Value-based classes warn that identity behaviour may change, so code that depends on which box it holds carries upgrade risk.

## What `compareAndSet` compares `AtomicReference<V>` holds one object reference that threads can update atomically. Its `compareAndSet(V expectedValue, V newValue)` sets the value to `newValue` only if the current value `== expectedValue`, and returns whether it did. On references, **`==` is identity**: it is true only when both operands refer to the same object or both are `null`. `equals()` is not called, so overriding it changes nothing here. The method's `@return` line says a `false` means the actual value "was not equal to" the expected one, which reads loosely; the sentence that defines the operation says `==`. The other compare methods on the class, `weakCompareAndSetPlain`, `weakCompareAndSetVolatile`, `compareAndExchange` and their acquire and release variants, use the same test. ## Why identity and not `equals()` **Compare-and-swap (CAS)** is one atomic step on one memory location: compare what is there, and write only on a match. What an `AtomicReference` stores is a reference, so a reference is what that step can compare. `equals()` is arbitrary Java code that may read many fields and take any amount of time while other threads run, so it cannot sit inside one atomic step. `AtomicInteger.compareAndSet(int, int)` has no such issue: the values it compares are primitive `int`s. ## The boxed value trap In an `AtomicReference<Integer>`, every `int` you pass is **autoboxed**, and javac compiles each boxing to a call to `Integer.valueOf(int)`, which "will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range". Inside that range the two boxes are one object. Outside it, JLS §5.1.7 "disallows any assumptions about the identity of the boxed values". The cache itself is a topic of its own; what matters here is what it does to a CAS: | Holder starts at | Call | Result at default flags | Why | |---|---|---|---| | `100` | `compareAndSet(100, 101)` | `true` | both boxes are the cached object | | `1000` | `compareAndSet(1000, 1001)` | `false` | two separate `Integer` objects | | `1000` | `compareAndSet(seen, seen + 1)`, with `seen` from `get()` | `true` | the reference it already holds | | `1000L` | `compareAndSet(1000L, 1001L)` | `false` | the JDK's `Long.valueOf` also stops caching at 127 | | `1.0` | `compareAndSet(1.0, 2.0)` | `false` | the JDK's `Double.valueOf` builds a new object each call | | `null` | `compareAndSet(null, x)` | `true` | `null == null` | This goes wrong in several ways: - **Silent failure.** The call returns `false`, throws nothing and leaves the value alone, so code that ignores the result loses the update. - **A retry loop that never ends.** `while (!ref.compareAndSet(1000, 1001)) {}` boxes a new `1000` on every attempt, so at default flags no attempt matches and the thread burns a core. - **It passes tests.** Small values work, so the failure can first appear with a production value outside that range. - **A flag changes the answer.** `-XX:AutoBoxCacheMax=2000` widens `Integer`'s cache and the `1000` call returns `true`. The JDK's `Long.valueOf` uses a fixed range, which no flag widens. - **The compiler is silent.** `javac -Xlint:all` compiles these calls without a warning. ## A freshly built equal object The rule is the same for any class. With `record Config(String url) {}`, `new Config("a")` can be `equals()` to the stored value and `compareAndSet(new Config("a"), next)` still returns `false`, because it is a second object. A `String` behaves the same way: `new String("ready")` does not match a stored `"ready"`, while the literal `"ready"` does, because string literals are interned. Enum constants are the safe case, since there is only one instance of each, which makes `AtomicReference` over an enum a sound small state machine. Identity also cuts the other way. A successful CAS shows that the reference is unchanged, not its contents. If the held object is mutable and another thread changed a field, `compareAndSet(seen, next)` succeeds and overwrites a state it never saw. So hold **immutable** objects, where a change always means a new reference. A reference that returns to an earlier value is the separate ABA problem. ## Writing it correctly - **Keep the reference you read.** Take `seen = ref.get()`, compute from it, call `compareAndSet(seen, next)`, and on `false` read again. If another thread stored an equal but separate box, the attempt fails and the loop simply re-reads. - **Let `updateAndGet` or `getAndUpdate` do that.** Their contract is to apply your function to the current value atomically, so you pass no expected value to re-box. The function should be side-effect-free, since it may be re-applied. In the JDK's implementation, each keeps the reference from `get()` and loops on `weakCompareAndSetVolatile(prev, next)`. - **Use a primitive holder for numbers.** `AtomicInteger` and `AtomicLong` avoid boxes entirely. `Integer`, `Long` and `Double` are also **value-based classes**, whose documentation says that for equal instances "a program should not attempt to distinguish between their identities" and that identity-related behaviour "may change in a future release". A CAS whose outcome depends on which box you hold is that kind of test, which is one more reason to prefer the primitive holders. ## Versions All of this is the same on JDK 25 and JDK 27. JEP 401, Value Objects, a preview feature integrated for JDK 28, goes further: with preview enabled, `Integer` instances are value objects and `==` compares their field values. JDK 27 has none of that.

  • The held object is mutable and another thread changed one of its fields in place. Does a CAS on the old reference notice?
    No. `==` sees the same reference, so `compareAndSet(seen, next)` succeeds and overwrites a state the caller never saw. That is why an `AtomicReference` should hold immutable objects: every change then means a new reference, and the CAS means what you expect. A reference that goes away and comes back is a different case, the ABA problem, which a stamp addresses.
  • What does compareAndExchange add over compareAndSet in a retry loop on AtomicReference?
    `compareAndExchange`, since 9, uses the same `==` test but returns the witness value, the reference it found, instead of a `boolean`. After a failure, that witness can be the next expected value with no separate `get()`. For a boxed value this helps, because the witness is the stored object itself and so it can pass the `==` test on the next attempt.
  • Can code rely on two equal Integer boxes staying distinct objects in later Java releases?
    No. `Integer` is a value-based class, and that documentation says identity-related behaviour may change in a future release. JEP 401, Value Objects, a preview feature integrated for JDK 28, makes `Integer` instances value objects when preview is on, with `==` comparing field values. JDK 27 does not have it, but it is a good reason not to write code that depends on which box it holds.

  • compareAndSet calls equals(), so any logically equal object will match.
  • Autoboxing always returns the same Integer object for the same int value.
  • A false return from compareAndSet always means another thread changed the value.
  • Overriding equals() and hashCode() makes compareAndSet treat equal objects as the same.
  • Retrying in a loop cures a failed CAS even if the expected value is re-boxed each try.
  • Small test values passing proves AtomicReference<Integer> works for every value.

AtomicReference.compareAndSet
Java 1.5
Integer.valueOf(int)
Java 1.5
AtomicReference.updateAndGet
Java 1.8

Assumes Java 27, and the same at 25: compareAndSet compares with == and a box's identity follows Integer.valueOf, which javac emits for boxing; JEP 401's value objects are a JDK 28 preview.

context