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

来源:互联网 发布:nginx 内置的全局变量 编辑:程序博客网 时间:2024/06/03 14:21

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
原创粉丝点击