Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference?

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.

like image 668
Anna Avatar asked Feb 22 '26 21:02

Anna


2 Answers

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.

like image 126
Mureinik Avatar answered Feb 25 '26 11:02

Mureinik


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);
like image 30
T.J. Crowder Avatar answered Feb 25 '26 11:02

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!