What is the difference between Atomic Integer and Normal immutable Integer class in Java? What is the difference between Atomic Integer and Normal immutable Integer class in Java? multithreading multithreading

What is the difference between Atomic Integer and Normal immutable Integer class in Java?


AtomicInteger is used in multithreaded environments when you need to make sure that only one thread can update an int variable. The advantage is that no external synchronization is requried since the operations which modify it's value are executed in a thread-safe way.

Consider the followind code:

private int count;public int updateCounter() {   return ++count;}

If multiple threads would call the updateCounter method, it's possible that some of them would receive the same value. The reason it that the ++count operation isn't atomical since isn't only one operation, but made from three operations: read count, add 1 to it's value and write it back to it. Multiple calling threads could see the variable as unmodified to it's latest value.

The above code should be replaced with this:

private AtomicInteger count = new AtomicInteger(0);public int updateCounter() {    return count.incrementAndGet();}

The incrementAndGet method is guaranteed to atomically increment the stored value and return it's value without using any external synchonization.

If your value never changes, you don't have to use the AtomicInteger, it's enought to use int.


AtomicInteger is thread safe (in fact, all classes from java.util.concurrent.atomic package are thread safe), while normal integers are NOT threadsafe.

You would require 'synchronized' & 'volatile' keywords, when you are using an 'Integer' variable in multi-threaded environment (to make it thread safe) where as with atomic integers you don't need 'synchronized' & 'volatile' keywords as atomic integers take care of thread safety.

Also, I would recommend the below helpful tutorial on the same subject:http://tutorials.jenkov.com/java-concurrency/compare-and-swap.html

Please refer below oracle doc for more information on 'atomic' package:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html


While immutable objects are thread-safe by definition, mutable objects can be thread safe too.

That is precisely the purpose of the Atomic... classes (AtomicInteger, AtomicBoolean, and so on).

The various ...get... and ...set... methods allow thread-safe access and mutation of the object.

Not surprisingly, the class is declared in the java.util.concurrent package.

You only have to browse the API for the java.util.concurrent.atomic package:

A small toolkit of classes that support lock-free thread-safe programming on single variables.