When is AtomicInteger preferrable over synchronized?

Viewed 12732

Since AtomicInteger can be at at least an order of magnitude slower than an int protected by synchronized, why would I ever want to use AtomicInteger?

For example, if all I want is to increment an int value in a thread-safe manner, why not always use:

synchronized(threadsafeint) {
  threadsafeint++;
}

instead of using the much slower AtomicInteger.incrementAndGet()?

2 Answers
Related