Why in AtomicIntegeror another Atomic class has define this set method?
example code:
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(int newValue) {
value = newValue;
}
or
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(V newValue) {
value = newValue;
}
this method not annotation atomic ?this set() method is mean he is not atomic yet?
i don't understand why in AtomicInteger or another Atomic (for example:AtomicReference) have no atomic method? thanks!
A write to or a read from a variable is an atomic operation per se - with the little exception of longs and doubles (see JLS §17.7).
Besides that the value field is declared as volatile, which makes getting and setting the value thread-safe because "the Java Memory Model ensures that all threads see a consistent value for the variable" (see JLS §8.3.1.4). Additionally, there is also a happens-before relationship when dealing with volatile variables (see JLS §17.4.5).
This means that the methods get and set are atomic operations per se without any further synchronizing mechanism. Other operations - such as getAndSet or compareAndSet - must use some further synchronization mechanisms to ensure atomicity.
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