robbin
robbin

Reputation: 1944

Can AtomicInteger replace synchronized?

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

Answers (5)

Jim Garrison
Jim Garrison

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

Stephen C
Stephen C

Reputation: 718816

Is volatile needed when I use AtomicInteger?

Not necessarily. Considering your example:

  • if i is a local variable, or
  • if i is a final attribute, or
  • if the current thread and the thread that initialized (or last updated) the i variable have synchronized after that event,

then it makes no difference if you declare i as volatile or not.

Upvotes: 1

John Vint
John Vint

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

Jonathan Holloway
Jonathan Holloway

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

GaryF
GaryF

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

Related Questions