The AtomicInteger class added in Java 5 in java.util.concurrent.atomic package. The AtomicInteger class provide way to perform atomic operation on int values. Its supports lock-free and thread-safe programming on single variables.The AtomicInteger class is wrapper class for int values which allows operations on it Atomically.
Atomic operations are performed as a single unit of task without interference of other operations or tasks. Atomic operations are required in multi-threaded environment to avoid data inconsistency. The AtomicInteger works based on Compare And Swap Algorithm.
To create a AtomicInteger We can simply use below given code to create a atomicInterger with initial value 0(zero) :
1 AtomicInteger atomicInteger = new AtomicInteger();
If there is requirement to create an AtomicInteger with an initial value, We can do by below code:
To get the value from AtomicInteger We can use it's get method to get from atomicInteger:
1 AtomicInteger atomicInteger = new AtomicInteger(100);//set initial value as 100
1 int myValue = atomicInteger.get();// gives 100
This class also provide a setter method to set value for atomicInteger , To get value We can use as:
AtomicInteger atomicInteger = new AtomicInteger(100);//set initial value as 100
atomicInteger.set(200);//update it's value from 100 to 200
int x = atomicInteger.get();// gives 200
To perform atomic arithmetical operation on int values, We can use AtomicInteger.
Like If We want to maintainer some counter in multi-threaded environment,In this case AtomicInteger class will ge very helpful.
<To Be Continued>