Volatile has the following effects:
Prevents reordering, guarantees visibility, and guarantees atomicity for a single read and write (excluding i++-like compound operations).
explained separately below.
It is well known (and perhaps some people don't) that the compiler and the CPU reorder the code without affecting the serial results in order to speed up execution. (such as superscalar pipeline calculation)
This can cause some problems in concurrent execution. Example of a DCL with a singleton pattern:
public class singleton{
Private Singleton () {};
public static volatile Singleton Singleton;
public static Singleton Getsingleton () {
if (singleton = = null) {
Synchronized (singleton) {
if (singleton = = null) {
Singleton = new Singleton ();
}
}
}
return singleton;
}
}
Double check lock good understanding, one is to ensure a single instance, but to reduce the concurrency overhead. Why use the volatile again?
Because the orange callout part actually has three steps:
Allocates memory, initializes the object, and references the assigned value.
However, because of the presence of reordering, it is possible to allocate memory first, then assign a value, and finally initialize. It is possible to expose an uninitialized object under concurrency. This is why it is used for volatile reasons.
After jdk1.5, there are happen-before relationship constraints in volatile semantics. Guarantees the write operation to the volatile object, which must be completed before the subsequent read operation.
It also eliminates the situation where this reordering causes errors.
Another visibility is that because threads have their own separate memory stacks, and global variables are typically inside heap memory, changes to a single thread may not be synchronized to the heap in time, causing the problem to change invisibly.
After adding the volatile, each change will force flush heap memory, and other thread stack memory, to ensure the latest data, that is, visibility.
Atomicity is to long,double this 64-bit variable, because the virtual machine is 32 bits, so the read and write to be divided two times, with volatile constraints, to ensure that the reading and writing of the atom.
It is important to note that the atomicity of the volatile guarantee is limited to this. For composite operations, such as I = i + 1; i++; This is not guaranteed.
So the atomicity of the compound operation is still to be ensured by synchronized.
The synchronized guarantees the strongest atomicity and visibility.
Java concurrency of Volatile