原子类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).

你可能感兴趣的:(原子类compareAndSet方法)