I stumbled across the source of AtomicInteger
and realized that
new AtomicInteger(0).equals(new AtomicInteger(0))
evaluates to false
.
Why is this? Is it some "defensive" design choice related to concurrency issues? If so, what could go wrong if it was implemented differently?
(I do realize I could use get
and ==
instead.)
This is partly because an AtomicInteger
is not a general purpose replacement for an Integer
.
The java.util.concurrent.atomic
package summary states:
Atomic classes are not general purpose replacements for
java.lang.Integer
and related classes. They do not define methods such ashashCode
andcompareTo
. (Because atomic variables are expected to be mutated, they are poor choices for hash table keys.)
hashCode
is not implemented, and so is the case with equals
. This is in part due to a far larger rationale that is discussed in the mailing list archives, on whether AtomicInteger
should extend Number
or not.
One of the reasons why an AtomicXXX class is not a drop-in replacement for a primitive, and that it does not implement the Comparable
interface, is because it is pointless to compare two instances of an AtomicXXX class in most scenarios. If two threads could access and mutate the value of an AtomicInteger
, then the comparison result is invalid before you use the result, if a thread mutates the value of an AtomicInteger
. The same rationale holds good for the equals
method - the result for an equality test (that depends on the value of the AtomicInteger
) is only valid before a thread mutates one of the AtomicInteger
s in question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With