Why is this an issue?

The equals method in AtomicInteger and AtomicLong returns true only if two instances are identical, not if they represent the same number value.

This is because equals is not part of the API contract of these classes, and they do not override the method inherited from java.lang.Object. Although both classes implement the Number interface, assertions about equals comparing number values are not part of that interface either. Only the API contract of implementing classes like Integer, Long, Float, BigInteger, etc., provides such assertions.

How to fix it

Code examples

Noncompliant code example

Boolean isSameNumberValue(AtomicLong a, AtomicLong b) {
  return a.equals(b); // Noncompliant, this is true only if a == b
}

Boolean isSameReference(AtomicLong a, AtomicLong b) {
  return a.equals(b); // Noncompliant, because misleading
}

Compliant solution

Boolean isSameNumberValue(AtomicLong a, AtomicLong b) {
  return a.get() == b.get(); // Compliant
}

Boolean isSameReference(AtomicLong a, AtomicLong b) {
  return a == b; // Compliant
}

Resources

Documentation

Articles & blog posts