不要使用equals方法对AtomicXXX进行是否相等的判断

1. “.equals()” should not be used to test the values of “Atomic” classes

级别:bug

AtomicInteger, and AtomicLong extend Number, but they’re distinct from Integer and Long and should be handled differently. AtomicInteger and AtomicLong are designed to support lock-free, thread-safe programming on single variables. As such, an AtomicInteger will only ever be “equal” to itself. Instead, you should .get() the value and make comparisons on it.

This applies to all the atomic, seeming-primitive wrapper classes: AtomicInteger, AtomicLong, and AtomicBoolean.

Noncompliant Code Example

AtomicInteger aInt1 = new AtomicInteger(0);
AtomicInteger aInt2 = new AtomicInteger(0);
if (aInt1.equals(aInt2)) { ... }  // Noncompliant

Compliant Solution

AtomicInteger aInt1 = new AtomicInteger(0);
AtomicInteger aInt2 = new AtomicInteger(0);
if (aInt1.get() == aInt2.get()) { ... }

Atomic类相等与否的判断不能使用equals()方法,Atomic的作用为了在多线程情况下保持单个变量的线程安全性。Atomic变量永远只会和自身相等,如果要判断Atomic变量是否相等,应该使用get()方法获取值之后再进行判断。

  • AtomicInteger VS Integer

Integer类重写了Objectequals()方法,根据值的大小判断是否相等:

/**
 * Compares this object to the specified object.  The result is
 * {@code true} if and only if the argument is not
 * {@code null} and is an {@code Integer} object that
 * contains the same {@code int} value as this object.
 *
 * @param   obj   the object to compare with.
 * @return  {@code true} if the objects are the same;
 *          {@code false} otherwise.
 */
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

AtomicInteger没有重写equals()方法,当使用equals()时,实际上使用的是Objectequals()方法,最终判断的是对象的地址是否相等。

public boolean equals(Object obj) {
    return (this == obj);
}

Objectequals()描述:只有当xy指向相同的引用时,equals()才返回true

for any non-null reference values {@code x} and {@code y}, this method returns {@code true} if and only if {@code x} and {@code y} refer to the same object

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值