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?
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
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:
As you can imagine that shouldn’t be the case, so you shouldn’t have to worry about the field being volatile.