lonecloud
lonecloud

Reputation: 413

AtomicInteger set method is Atomic?

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!

Upvotes: 3

Views: 2678

Answers (3)

Seelenvirtuose
Seelenvirtuose

Reputation: 20608

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.

Upvotes: 2

Antho Christen
Antho Christen

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

user9455968
user9455968

Reputation:

Because AtomicInteger provides additional methods like public final int getAndSet(int newValue) for operations that must be atomic.

Upvotes: 0

Related Questions