Skip to main content

The "volatile" Keyword

The volatile keyword associated with a specific variable indicates that this variable cannot be optimized (placed in a register or excluded from conditions based on compile-time invariants). Every read or write operation associated with this variable will work directly with the RAM memory. This is useful in preventing incompatible optimizations when combined with modifying the value from another thread or reading outdated data from the core's register associated with the thread when the variable has received a new value from another thread.

public static volatile int counter = 0;
caution

It is important to mention that volatile variables increase the program's execution time because every modification made to them must be propagated to other threads, while normal variables can be cached up to the processor's register level at some point (in the case of a loop counter).