Java volatile Keyword

<< synchronized Keyword

Learn More on Java >>





volatile keyword is used on variables. Understanding volatile variable requires understanding of atomic action.

Atomic action is any action that either happens or does not happen. There is no possibility of partial happening.

Read and writes are atomic for reference variables and for primitive data types except long and double. Reads and Writes are atomic for all types of variables declared as volatile

JVM optimizations cause the variables to be read and cached in some situations and thus read is not done every single time. This is good when there is only thread accessing these variables. However, this is not good when multiple threads access the variable.

Whenever you have multiple threads accessing the same variable, volatile keyword is used on the variable to make sure that the value is read every time

volatile may not find its use in all scenarios. However, when there is a scenario in which java optimizes memory reads and you foresee that value that your code takes, is not the latest value. In such scenarios, volatile should be used.

Usage


	static long count=0l;
	static volatile float real=1.5f;
	volatile List obj=new ArrayList();

<< synchronized Keyword

Learn More on Java >>





Java volatile Keyword

<< synchronized Keyword

Learn More on Java >>





volatile keyword is used on variables. Understanding volatile variable requires understanding of atomic action.

Atomic action is any action that either happens or does not happen. There is no possibility of partial happening.

Read and writes are atomic for reference variables and for primitive data types except long and double. Reads and Writes are atomic for all types of variables declared as volatile

JVM optimizations cause the variables to be read and cached in some situations and thus read is not done every single time. This is good when there is only thread accessing these variables. However, this is not good when multiple threads access the variable.

Whenever you have multiple threads accessing the same variable, volatile keyword is used on the variable to make sure that the value is read every time

volatile may not find its use in all scenarios. However, when there is a scenario in which java optimizes memory reads and you foresee that value that your code takes, is not the latest value. In such scenarios, volatile should be used.

Usage


	static long count=0l;
	static volatile float real=1.5f;
	volatile List obj=new ArrayList();

<< synchronized Keyword

Learn More on Java >>