Reputation: 1944
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?
Upvotes: 19
Views: 18629
Reputation: 86774
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.
Upvotes: 9
Reputation: 718816
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.
Upvotes: 1
Reputation: 40256
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.
Upvotes: 18
Reputation: 63672
AtomicInteger uses sun.misc.Unsafe underneath to perform the atomic updates.
So, in answer to your question, yes, AtomicInteger is thread-safe.
Upvotes: 2
Reputation: 24340
Yes, they're functionally equivalent.
If you're in an ultra-high contention environment, you may see performance differences, but that's highly unlikely.
Upvotes: 4