As Integer class is also immutable class and we know that immutable class is thread-safe what is the need of Atomic Integer. I am confused . Is it the reason that reads and write of immutable objects need not be atomic whereas read and write of atomic integer is atomic . That means atomic classes are also thread-safe.
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.
You can't alter an immutable object! A: The answer to your question is simple: once an Integer instance is created, you cannot change its value. The Integer String , Float , Double , Byte , Long , Short , Boolean , and Character classes are all examples of an immutable class.
Save 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.
compareAndSet() is an inbuilt method in java that sets the value to the passed value in the parameter if the current value is equal to the expected value which is also passed in the parameter. The function returns a boolean value which gives us an idea if the update was done or not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With