Can you explain me what is the difference between
i.compareAndSet(i.get(), i.get() + 1)
and
int s = i.get();
int nextS = s + 1;
i.compareAndSet(s, nextS);
where i is an AtomicInteger. Am I right that first way is wrong if I want to get increment value of i? But I can't explain why.
The first way calls i.get() twice. Since there's no locking here, the two calls may return different values, which is probably not what you expected.
I want to get next value of int
Then you probably don't want compareAndSet at all, you want updateAndGet:
updated = i.updateAndGet(value -> value + 1);
Or getAndUpdate if you want the previous value before it was updated:
previous = i.getAndUpdate(value -> value + 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With