SonarQube-Java规范之Atomic-".equals()" should not be used to test the values of "Atomic" classes

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.

AtomicInteger类和AtomicLong类继承自Number类,但是它们与Integer类和Long类有不同点,因此在使用上也有不同。AtomicInteger类和AtomicLong类是为支持单个变量的线程安全和无需锁定而设计的。因此,一个AtomicInteger对象的".equals()"方法比较只有在跟自己比较的时候才会返回true。所以,对于比较它们的值是否相等,就应当使用AtomicInteger对象的”.get()“方法,进行取值比较。

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

这条规则适用于所有的atomic类对象,具体参考封装类:AtomicInteger,AtomicLong和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()) { ... }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值