为什么两个 AtomicInteger 永远不相等? [英] Why are two AtomicIntegers never equal?

查看:32
本文介绍了为什么两个 AtomicInteger 永远不相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了 AtomicInteger 的来源并意识到

I stumbled across the source of AtomicInteger and realized that

new AtomicInteger(0).equals(new AtomicInteger(0))

计算结果为 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.)

推荐答案

这部分是因为 AtomicInteger 不是 Integer 的通用替代品.

This is partly because an AtomicInteger is not a general purpose replacement for an Integer.

java.util.concurrent.atomic 包摘要 状态:

原子类不是通用的替代品java.lang.Integer 和相关类.他们没有定义方法例如 hashCodecompareTo.(因为原子变量是预计会发生变异,它们是哈希表键的糟糕选择.)

Atomic classes are not general purpose replacements for java.lang.Integer and related classes. They do not define methods such as hashCode and compareTo. (Because atomic variables are expected to be mutated, they are poor choices for hash table keys.)

hashCode 未实现,equals 也是如此.这部分是由于在邮件列表存档,关于AtomicInteger 是否应该扩展Number.

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 AtomicIntegers in question.

这篇关于为什么两个 AtomicInteger 永远不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆