Java Interview Question
Use this advanced question and answer to prepare for your next Java interview.
What is the use of the
volatile keyword in Java? What is the happens-before guarantee?
volatile keyword is used in multi-threaded programs. It indicates that a variable can be updated by multiple threads. This means that the value of the variable cannot be cached locally and must be directly accessed from main memory every time.
volatile variables are not serializable.
The happens-before guarantee for
volatile variables can be explained as follows:
volatilevariable results in the writing of all local variables to the main memory. So, any other thread accessing common variables will get all updated values whenever a
volatilevariable is updated.
volatilevariables cannot be reordered by the compiler. Any statements following access to a
volatilevariable are guaranteed to be executed after the access statement.