Volatile

Volatile is a keyword within the java programming language that specifies that a member variable associated with a class can be altered asynchronously by multiple threads. The volatile keyword in the code acts as a modifier when a member is declared. Keywords are fundamentally reserved words with a distinct meaning in the context of a compiler.
The volatile keyword is used whenever the variable signifies some sort of variable that is dependent on the environment or system, such as simple counters and clocks.

The volatile keyword ensures that each read access to a member variable returns the most recent value of it. This is not effective when the recent changes are done using a different thread. If a member variable is not declared as volatile, a thread will not be able to recognize the modifications done to it using a different thread.
For a double or long member, the volatile keyword also ensures that the virtual machine will not generate two successive 32-bit writes, but will create just one 64-bit write instead. If this is not feasible, the JVM implementation continues to ensure the atomicity of this function in order that the old lower half will not be read with the new higher half of some volatile double or long.
Volatile writes and reads set up a happens-before relationship. Before a volatile object is accessed, a synchronization occurs between the main memory and the cached variables, just as it occurs prior to entering or after leaving a synchronized block. This implies that a volatile object can be safely published without synchronization; that is, when a volatile object is accessed by a thread, the members of that object are also updated.
When a variable is described as volatile, JVM and Java compiler perform the following two things.
  1. The compiler fails to maximize the statements and expressions related to that variable.
  2. JVM synchronizes the variable.
The advantages of volatile are as follows:
  • It's lightweight
  • It causes a very small overhead to reads and writes, but is still faster than locking.
  • Volatile is resistant to dead locks.

Post a Comment

0 Comments