Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AtomicInteger set method is Atomic?

Tags:

java

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!

like image 495
lonecloud Avatar asked Sep 03 '26 07:09

lonecloud


1 Answers

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.

like image 107
Seelenvirtuose Avatar answered Sep 05 '26 20:09

Seelenvirtuose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!