The javadoc for the java.util.concurrent.atomic package says the following:
A small toolkit of classes that support lock-free thread-safe programm
Yes, they're functionally equivalent.
If you're in an ultra-high contention environment, you may see performance differences, but that's highly unlikely.
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.
Is volatile needed when I use AtomicInteger?
Not necessarily. Considering your example:
i
is a local variable, ori
is a final
attribute, ori
variable have synchronized after that event,then it makes no difference if you declare i
as volatile or not.
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.
AtomicInteger uses sun.misc.Unsafe underneath to perform the atomic updates.
So, in answer to your question, yes, AtomicInteger is thread-safe.