How can I do “check-then-act” in an AtomicInteger variable?
I.e. what is the most safe/best way to check the value of such a variable first and inc/dec depending on result?
E.g. (in high level)
if(count < VALUE) count++; //atomically using AtomicInteger
How can I do check-then-act in an AtomicInteger variable? I.e. what is the most
Share
You need to write a loop. Assuming that
countis yourAtomicIntegerreference, you would write something like:The above will loop until either: (1) your
if(count < VALUE)condition is not satisfied; or (2)countis successfully incremented. The use ofcompareAndSetto perform the incrementation lets us guarantee that the value ofcountis stilloldCount(and therefore still less thanVALUE) when we set its new value.