Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volatile keyword behavior after version 1.5

Tags:

java

volatile

In this tutorial in the Java volatile Happens-Before Guarantee section, there's a sentence regarding the happens-before rule:

The reading and writing instructions of volatile variables cannot be reordered by the JVM (the JVM may reorder instructions for performance reasons as long as the JVM detects no change in program behaviour from the reordering).

My question is how the JVM detects the re-ordering of instructions. Can we have any example, specification, or notes written anywhere which give more understanding about JVM performance due to reordering of instructions? I could not find anything useful online.

like image 515
V.S Avatar asked Jan 31 '26 11:01

V.S


1 Answers

Instructions can be reordered to ensure that a pipeline does not stall. Say you have a sequence of instructions and each instruction depends in some way on the previous instruction. Then the processor cannot execute these instructions in parallel because the execute stage (or sometimes even the decode stage) of each instruction (from fetch, decode, execute and store) cycle will depend on the execute stage of the previous instruction and hence bubbles or nop (no-operation) need to be introduced.

To prevent this, the JVM or the hardware can reorder instructions such that the dependency on a prior instruction does not stall the pipeline by executing some other non dependent instruction in between. In doing so it is the job of the JVM or the hardware to ensure that reordering instructions does not in any way alter the behavior of the program had it been executed sequentially.

volatile keyword guarantees that the state of variables written to (which can be non-volatile) before the volatile write is visible to any thread that reads the value written into the volatile variable. This is like synchronization albeit a weaker form of it. In other words, the use of volatile guarantees that any memory write before the write to the volatile variable is not reordered to happen after the write to the volatile variable. Likewise any read of a variable after a volatile read is guaranteed to not be reordered to happen before the read from the volatile variable.

A JVM can prevent instruction reordering by adding a fence instruction which prevents optimizations on the instructions around the fence.

like image 197
MS Srikkanth Avatar answered Feb 03 '26 00:02

MS Srikkanth