Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance Difference of AtomicInteger vs Integer

Is there any performance difference between AtomicInteger and Integer?

like image 897
Boni Avatar asked Jan 16 '12 10:01

Boni


People also ask

Is AtomicInteger slower than Integer?

Bookmark this question. Show activity on this post. I testes how fast the Atomic Integer in multithread with comparing synchronized method, but I got the result that Atomic Integer was slower than synchronized method.

What is difference between AtomicInteger and Integer?

Integers are object representations of literals and are therefore immutable, you can basically only read them. AtomicIntegers are containers for those values. You can read and set them. Same as asigning a value to variable.

What is AtomicInteger and when to use?

An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes. Since: 1.5 See Also: Serialized Form.

Is AtomicInteger volatile?

This is source code of AtomicInteger. The value is Volatile. So,AtomicInteger uses Volatile inside.


2 Answers

The choice of these two types should not depend on the performance. The main choice for AtomicInteger is if you want to achieve thread safety with the operations on the integer.

However the performace difference might strongly depend on the choosen operating system, as the detailed implementation of atomic operations depend on the operating system.

like image 115
tune2fs Avatar answered Oct 03 '22 03:10

tune2fs


AtomicInteger allows some (not all!) operations that would otherwise require synchronization to be performed in a lock-free manner using special hardware instructions. How this affects performance is somewhat complex:

  • First, it's a micro-optimization that will only matter if this particular operation is on your application's critical path.
  • The special hardware instructions may not be available on non-mainstream platforms, in which case AtomicInteger will probably be implemented using synchronization.
  • The JVM can often optimize away locking overhead when there is no contention (e.g., a single threaded application). In that case, there's probably no difference.
  • If there is low to moderate lock contention (i.e. multiple threads, but they mostly do other things than just accessing that integer), the lock-free algorithm performs better than synchronization.
  • If there is very heavy lock contention (i.e. lots of threads that spend a lot of time trying to access that integer), synchronization may perform better because the lock-free algorithm is based on constantly retrying the operation when it fails due to a collision.
like image 26
Michael Borgwardt Avatar answered Oct 03 '22 05:10

Michael Borgwardt