为什么两个AtomicIntegers从不相等? [英] Why are two AtomicIntegers never equal?
问题描述
我偶然发现了 AtomicInteger
的来源,意识到
I stumbled across the source of AtomicInteger
and realized that
new AtomicInteger(0).equals(new AtomicInteger(0))
false 。
equals 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?
(我意识到我可以使用 get
==
。)
(I do realize I could use get
and ==
instead.)
推荐答案
c $ c> AtomicInteger 不是 Integer
的通用替代。
This is partly because an AtomicInteger
is not a general purpose replacement for an Integer
.
java.util.concurrent.atomic
package summary 说明:
原子类不是$ b $的通用替换b
java.lang.Integer
和相关类。它们不定义方法
,如hashCode
和compareTo
。 (因为原子变量是
,期望被改变,所以它们对于散列表键是很差的选择。)
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
未实现,因此 equals
的情况也是如此。这部分是由于更大的理由,即在邮件列表存档中讨论 a>,关于 AtomicInteger
是否应该扩展数字
。
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.
AtomicXXX类不是基本类型的插入替换,并且不实现 Comparable
接口的原因之一是因为它是无意义的在大多数情况下比较AtomicXXX类的两个实例。如果两个线程可以访问和改变 AtomicInteger
的值,那么在使用结果之前,比较结果无效,如果一个线程突变了 AtomicInteger
的值。同样的原理适用于 equals
方法 - 等式测试的结果(取决于 AtomicInteger
)仅在线程突变了有问题的 AtomicInteger
之一之前有效。
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.
这篇关于为什么两个AtomicIntegers从不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!