Why does AtomicInteger have both a int get() and an int intValue()? I see it also has float floatValue() among others, from Number. Does one have implications related to maintaining atomicity of the AtomicInteger param, or are both interchangeable?
AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables.
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.
If you want to create an AtomicInteger with an initial value, you can do so like this: AtomicInteger atomicInteger = new AtomicInteger(123); This example passes a value of 123 as parameter to the AtomicInteger contructor, which sets the initial value of the AtomicInteger instance to 123 .
Yes, you are correct. AtomicInteger would not grant any benefit if all access to the object is synchronized (only one thread, at most, would be accessing its contents at any given moment).
They should be interchangeable. Here is the relevant part of the source code for AtomicInteger:
public int intValue() {
return get();
}
intValue definition:
/**
* Returns the value of this {@code AtomicInteger} as an {@code int}.
*/
public int intValue() {
return get();
}
get definition:
/**
* Gets the current value.
*
* @return the current value
*/
public final int get() {
return value;
}
You can clearly see that get method is final. final methods cannot be overridden.
If we extend the AtomicInteger class, we cannot override the get method, but we can override the intValue method.
From Number class documentation:
The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.
From AtomicInteger documentation
Description copied from class:
Number Returns the value of the specified number as an int. This may involve rounding or truncation.
As AtomicInteger extends abstract class Number, abstract method intValue() has to be implemented. They are equal in this case. For other types (e.g. BigDecimal, Double or Float) it makes much more sense.
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