The javadoc for the java.util.concurrent.atomic package says the following:
A small toolkit of classes that support lock-free thread-safe programming on single variables.
But I don't see any thread-safe (synchronized or Lock) code inside any of the AtomicInteger or AtomicBoolean classes.
So, are these 2 the same:
1.
int i;
synchronized(this){i++;}
2.
AtomicInteger i = new AtomicInteger();
i.getAndIncrement();
Update: Thanks for the answers. Is volatile needed when I use 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.
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.
Integers are object representations of literals and are therefore immutable, you can basically only read them. AtomicIntegers are containers for those values. You can read and set them.
It's also possible to achieve thread-safety using the set of atomic classes that Java provides, including AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization.
They would offer the same atomicity. The only thing you must be aware of is any time you read i you must wrap it with synchronized also
synchronized(this){ return i;}
Edit to answer your edit:
Volatile is not necessary for your AtomicInteger. To prove that declare the AtomicInteger final. The only reason you would need the AtomicInteger to be volatile is if the AtomicInteger field itself changes. Similar to:
volatile AtomicInteger i = new AtomicInteger(0);
public void work(){
i.incrementAndGet();
//...do some other stuff
i = new AtomicInteger(10);//because the field i is changing the field needs to be volatile
}
As you can imagine that shouldn't be the case, so you shouldn't have to worry about the field being volatile.
They are equivalent functionally, but there is a subtle difference. synchronized
has the overhead of acquiring and releasing the monitor on this
, while AtomicInteger
is implemented with a native method call, so it will be significantly faster.
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