Volatile (computer programming)

In computer programming, particularly in the C, C++, C#, and Java programming languages, the volatile keyword indicates that a value may change between different accesses, even if it does not appear to be modified. This keyword prevents an optimizing compiler from optimizing away subsequent reads or writes and thus incorrectly reusing a stale value or omitting writes. Volatile values primarily arise in hardware access (memory-mapped I/O), where reading from or writing to memory is used to communicate with peripheral devices, and in threading, where a different thread may have modified a value.
Despite being a common keyword, the behavior of codice_1 differs significantly between programming languages, and is easily misunderstood. In C and C++, it is a type qualifier, like codice_2, and is a property of the "type". Furthermore, in C and C++ it does "not" work in most threading scenarios, and that use is discouraged. In Java and C#, it is a property of a variable and indicates that the object to which the variable is bound may mutate, and is specifically intended for threading. In the D programming language, there is a separate keyword codice_3 for the threading usage, but no codice_1 keyword exists.
In C and C++.
In C, and consequently C++, the codice_1 keyword was intended to
Operations on codice_1 variables are not atomic, nor do they establish a proper happens-before relationship for threading. This is specified in the relevant standards (C, C++, POSIX, WIN32), and volatile variables are not threadsafe in the vast majority of current implementations. Thus, the usage of codice_1 keyword as a portable synchronization mechanism is discouraged by many C/C++ groups.
Example of memory-mapped I/O in C.
In this example, the code sets the value stored in codice_11 to codice_12. It then starts to poll that value repeatedly until it changes to codice_13:
static int foo;
void bar(void) {
 foo = 0;
 while (foo != 255)
An optimizing compiler will notice that no other code can possibly change the value stored in codice_11, and will assume that it will remain equal to codice_12 at all times. The compiler will therefore replace the function body with an infinite loop similar to this:
void bar_optimized(void) {
 foo = 0;
 while (true)
However, codice_11 might represent a location that can be changed by other elements of the computer system at any time, such as a hardware register of a device connected to the CPU. The above code would never detect such a change; without the codice_1 keyword, the compiler assumes that the current program is the only part of the system that could change the value (which is by far the most common situation).
To prevent the compiler from optimizing code as above, the codice_1 keyword is used:
static volatile int foo;
void bar (void) {
 foo = 0;
 while (foo != 255)
With this modification the loop condition will not be optimized away, and the system will detect the change when it occurs.
Generally, there are memory barrier operations available on platforms (which are exposed in C++11) that should be preferred instead of volatile as they allow the compiler to perform better optimization and more importantly they guarantee correct behaviour in multi-threaded scenarios; neither the C specification (before C11) nor the C++ specification (before C++11) specifies a multi-threaded memory model, so volatile may not behave deterministically across OSes/compilers/CPUs).
Optimization comparison in C.
The following C programs, and accompanying assemblies, demonstrate how the codice_1 keyword affects the compiler's output. The compiler in this case was GCC.
While observing the assembly code, it is clearly visible that the code generated with codice_1 objects is more verbose, making it longer so the nature of codice_1 objects can be fulfilled. The codice_1 keyword prevents the compiler from performing optimization on code involving volatile objects, thus ensuring that each volatile variable assignment and read has a corresponding memory access. Without the codice_1 keyword, the compiler knows a variable does not need to be reread from memory at each use, because there should not be any writes to its memory location from any other thread or process.
C++11.
According to the C++11 ISO Standard, the volatile keyword is only meant for use for hardware access; do not use it for inter-thread communication. For inter-thread communication, the standard library provides codice_24 templates.
In Java.
The Java programming language also has the codice_1 keyword, but it is used for a somewhat different purpose. When applied to a field, the Java qualifier codice_1 provides the following guarantees:
Using codice_1 may be faster than a lock, but it will not work in some situations before Java 5. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.
In C#.
In C#, codice_1 ensures that code accessing the field is not subject to some thread-unsafe optimizations that may be performed by the compiler, the CLR, or by hardware. When a field is marked codice_1, the compiler is instructed to generate a "memory barrier" or "fence" around it, which prevents instruction reordering or caching tied to the field. When reading a codice_1 field, the compiler generates an "acquire-fence", which prevents other reads and writes to the field, including those in other threads, from being moved "before" the fence. When writing to a codice_1 field, the compiler generates a "release-fence"; this fence prevents other reads and writes to the field from being moved "after" the fence.
Only the following types can be marked codice_1: all reference types, codice_33, codice_34, codice_35, codice_36, codice_37, codice_38, codice_39, codice_40, codice_41, and all enumerated types with an underlying type of codice_35, codice_36, codice_37, codice_38, codice_39, or codice_40. (This excludes value structs, as well as the primitive types codice_48, codice_49, codice_50 and codice_51.)
Using the codice_1 keyword does not support fields that are passed by reference or captured local variables; in these cases, codice_53 and codice_54 must be used instead.
In effect, these methods disable some optimizations usually performed by the C# compiler, the JIT compiler, or the CPU itself. The guarantees provided by codice_53 and codice_54 are a superset of the guarantees provided by the codice_1 keyword: instead of generating a "half fence" (ie an acquire-fence only prevents instruction reordering and caching that comes before it), codice_58 and codice_59 generate a "full fence" which prevent instruction reordering and caching of that field in both directions. These methods work as follows:
The codice_53 and codice_54 methods generate a full fence by calling the codice_66 method, which constructs a memory barrier that works in both directions. In addition to the motivations for using a full fence given above, one potential problem with the codice_1 keyword that is solved by using a full fence generated by codice_66 is as follows: due to the asymmetric nature of half fences, a codice_1 field with a write instruction followed by a read instruction may still have the execution order swapped by the compiler. Because full fences are symmetric, this is not a problem when using codice_66.
In Fortran.
codice_71 is part of the Fortran 2003 standard, although earlier version supported it as an extension. Making all variables codice_1 in a function is also useful finding aliasing related bugs.
integer, volatile :: i ! When not defined volatile the following two lines of code are identical
write(*,*) i**2 ! Loads the variable i once from memory and multiplies that value times itself
write(*,*) i*i ! Loads the variable i twice from memory and multiplies those values
By always "drilling down" to memory of a VOLATILE, the Fortran compiler is precluded from reordering reads or writes to volatiles. This makes visible to other threads actions done in this thread, and vice versa.
Use of VOLATILE reduces and can even prevent optimization.