原子类compareAndSet方法

compareAndSet() returns true if the current value equals the expected value v, and thus the value was updated to v + 1.

In your first version, if both threads get the same initial value then one will succeed (updating to v + 1) and the other will fail (since the current value is no longer v) and retry using v + 1 and v + 2.

If this code is intended to return unique keys then the first version is correct, since at the point compareAndSet() returned true the current value is guaranteed to be v + 1 (even if only briefly). The second version may return duplicate values due to a race condition if another thread modifies the value in between your calls to compareAndSet() and get().

That said, you might want to investigate AtomicInteger's incrementAndGet() method, which does pretty much the same thing but more efficiently (no explicit looping).

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容