Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare AtomicInteger without setting it

Tags:

java

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.

like image 820
peter.petrov Avatar asked Sep 30 '15 11:09

peter.petrov


People also ask

Why is AtomicInteger class better than a synchronized counter class What is CAS?

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.

Is AtomicInteger slow?

New! Save questions or answers and organize your favorite content. Learn more.

What is AtomicInteger and when to use?

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.

How do you make a new AtomicInteger with the given initial value?

AtomicInteger atomicInteger = new AtomicInteger(); This example creates an AtomicInteger with the initial value 0 .


2 Answers

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.

like image 190
assylias Avatar answered Sep 29 '22 02:09

assylias


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.

like image 30
Suresh Atta Avatar answered Sep 29 '22 00:09

Suresh Atta