How can I compare an AtomicInteger
with a given int
value without setting the AtomicInteger
to a new value? I don't see such a method in AtomicInteger
.
AtomicInteger class of atomic package uses a combination of volatile and CAS (compare and swap) to achieve thread-safety for Integer Counter. It is non-blocking in nature and thus highly usable in writing high throughput concurrent data structures that can be used under low to moderate thread contention.
New! Save questions or answers and organize your favorite content. Learn more.
An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
AtomicInteger atomicInteger = new AtomicInteger(); This example creates an AtomicInteger with the initial value 0 .
by the time get() returns, the value in the AtomicInteger may get updated to a new value... so I may get a stale value
By definition, if the value in the atomic integer gets updated right after you call int i = atomic.get()
you will have a stale value in i
. But that's just how concurrent programs work - when you consult a value, you know that it may already have changed.
What AtomicInteger::get
guarantees is that when you call it, you will get the latest value available at the time of the call. A guarantee which you would not have with a plain int
for example.
In other words, imagine the program below:
if (atomic.get() == 0) print("zero");
Even if you had some sort of compareButNotSet
method, it would not help because by the time you reach the print statement the value of atomic may have changed anyway...
If you need to make sure that print is only called if the value is still 0, you need to synchronize (or use a lock around) the whole block.
You have get()
method for it
Gets the current value.
Returns:
the current value
You need not to worry about that synchronised part since you compare that at particular point.
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