Friday, 22 April 2016

What is volatile keyword in Java ?


Volatile variables ensure that updates to variable are propagated to other threads.

All the threads read it’s value directly from the memory and not from registers or cache. So, read of a volatile variable always returns most recent write by any thread.

When thread A writes to a volatile variable and subsequently thread B reads the same variable, the values of all variables that were visible to A prior to writing to the volatile variable become visible to B after reading the volatile variable.

Writing a volatile variable is like exiting a sync block.
Reading a volatile variable is like entering a sync block.

volatile boolean isok;
// ------
    while(isok) {
       // -------
    }

Typical use
  • Checking status flag to decide to exit a loop
  • Ensuring visibility of their own state

No comments:

Post a Comment

Note: only a member of this blog may post a comment.