Sunday, 19 July 2015

Volatile variable in java

In java, volatile variables are weaker form of synchronization, to ensure that updates to a variable are propagated predictably to other threads. When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations.Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread. Yet accessing a volatile variable performs no locking and so can not cause the executing thread to block, making volatile variable a lighter-weight synchronization mechanism than synchronize.

                  The visibility effects of a volatile variables extend beyond the value of the volatile variable itself. When thread A writes to a volatile variable and subsequently thread B reads that same variable, the value of all variables that were visible to A prior to writing to volatile variable become visible to B after reading the volatile variable.

Locks Vs Volatile:
  Locking can guarantee  both visibility and atomicity; volatile variables can only guarantee only visibility.

When to use volatile variables:
 We have to use volatile variables when all the following criteria are met:
  •  Write to the variables do not depend on its current value, or we can ensure that only a single thread ever updates the value.
  • The variable does not participate in invariants(exit condition) with other state variables and
  • Locking is not required for any other reason while the variable is being accessed.

No comments:

Post a Comment