• 1 reply
  • Latest Post - ‏2005-08-12T14:51:16Z by SystemAdmin
1240 Posts

Pinned topic Regarding "volatile"

‏2005-08-12T06:14:36Z |
Friends i found myself unable to differentiate b/w normal variables and those declared as volatile for eg. no difference found b/w "int i" and "volatile int i". Please refer to any working example which can show me real diffrernce, i.e JVM optimizeses volatile variables. Please also tell me the exact meaning of "optimization" here.

waiting for reply.
Prateek Jain
Updated on 2005-08-12T14:51:16Z at 2005-08-12T14:51:16Z by SystemAdmin
  • SystemAdmin
    1240 Posts

    Re: Regarding "volatile"

    Compilers are allowed to cache variables in registers, to improve performance. Values in registers are not visible to other threads.

    Processors may have per-processor caches that are not always visible to other processors (not all architectures support cache coherence.) Therefore, processor 1 may see a different value in memory location X than processor 2.

    All of this is anticipated by the memory model; if you intend to share a variable across threads, you use synchronization.

    Volatile is a "lite" form of synchronization, where you are giving the compiler/runtime hints that "this variable is definitely going to be of interest to other threads, so don't cache it anywhere where they can't see it."

    This inhibits certain compiler optimizations (such as hoisting the value into a register) and cache optimizations (ensuring cache flushes after writing a volatile or before reading one) so that the value is communicated across threads on a more timely basis.

    For example:

    boolean asleep;
    int sheep = 0;

    while (!asleep)

    If 'asleep' is not volatile, the compiler can transform this into:

    if (!asleep) {
    while (true)

    because it can see that the loop body does not modify 'asleep'. But with 'asleep' as volatile, it will not perform this optimization, because it is aware that the value might change asynchronously.