liveBook · Manning

Atomic type

As explained in 100 Java Mistakes and How to Avoid Them

An atomic variable is a Java concurrency object that supports indivisible access and updates to a stored value.

Atomic variables such as AtomicInteger and AtomicReference support concurrent updates, but equals() does not compare their stored payloads. Read the values explicitly with get() when value comparison is actually appropriate. section 7.2

var v1 = new AtomicInteger(1);
var v2 = new AtomicInteger(1);
System.out.println(v1.equals(v2));    #1
System.out.println(v1.get() == v2.get());     #2

Compare the wrapper objects with equals(), then compare their current stored values with get(). The second comparison expresses payload equality. section 7.2

Use this rule cautiously:

  • Do not assume two atomic variables are equal because their values matched once; concurrent updates can change that relationship immediately afterward. section 7.2
  • Compare atomic values only when updates have finished, or when the application explicitly accepts the timing of the comparison. section 7.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains payload access and timing consequences, but stops short of detailing atomic update internals.
Examples
Uses paired AtomicInteger instances to contrast equals() with get()-based value comparison.
What it assumes
Assumes familiarity with Java objects, equals(), AtomicInteger, AtomicReference, and concurrent updates.
What you can do after
Diagnose and correct atomic-value equality checks with explicit get() calls and update-timing checks.
How it connects
Connects atomic variables with equals(), get(), AtomicInteger, AtomicReference, and concurrent updates.

Also explained in

Compare how 17 books explain atomic type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.