What operations are atomic operations

I'm a little confused...

Is it true that reading / writing from several streams, except long and double, are atomic operations, and you need to use volatile only with long and double?

+6
source share
4 answers

It looks like you are referring to this section of JLS. It is guaranteed for all primitive types - except for double and long - that all threads will see some value that was actually written to this variable. (With double and long first four bytes could be written by one stream, and the last four bytes by another stream, as indicated in this JLS section.) But they will not necessarily see the same value at the same time if the variable is not marked volatile .

Even using volatile , x += 3 not atomic, because it is x = x + 3 , which reads and writes, and can be written to x between read and write. This is why we have things like AtomicInteger and other utilities in java.util.concurrent .

+8
source

Do not confuse atomic flows. Long and double entries are not atomic, because each of them represents two separate 32-bit storages. Storing and loading short-lived / double fields is absolutely atomic if they are not a composite record (e.g. i++ ).

By atomic, I mean that you will not read some distorted object as a result of the fact that many streams write different objects in the same field.

From Java Concurrency In Practice 3.1.2

Non-standard security: when a stream reads a variable without synchronization, it can see an outdated value, but at least it sees a value that was actually placed there by some stream, and not some random value. This is true for all variables except 64-bit and double, which are unstable. JVMs are allowed to handle 64-bit read or write as two separate 32-bit operations that are not atomic.

+3
source

It doesn’t sound like that.

An atomic operation is an operation that causes all threads to wait for access to a resource until another thread is executed with it. I do not understand why other types of data will be atomic and others not.

0
source

volatile has a different semantics than just writing a value atomically

this means that other threads can immediately see the updated value (and that it cannot be optimized)

0
source

Source: https://habr.com/ru/post/912260/


All Articles