Reputation: 413
Why in AtomicInteger
or 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!
Upvotes: 3
Views: 2678
Reputation: 20608
A write to or a read from a variable is an atomic operation per se - with the little exception of long
s and double
s (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.
Upvotes: 2
Reputation: 1329
The operation is , per-se, automic, as it has only one instruction. So there is no need for any synchronization, unlike the other methods like getAndSet
, for which too the documentation says that they have been ensured to work atomically .
Upvotes: 0
Reputation:
Because AtomicInteger
provides additional methods like public final int getAndSet(int newValue)
for operations that must be atomic.
Upvotes: 0