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?


The 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:

  • Writing of a volatile variable 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 volatile variable is updated.
  • Access to volatile variables cannot be reordered by the compiler. Any statements following access to a volatile variable are guaranteed to be executed after the access statement.

Looking for developers?

Want to learn more about Gigster? Enter your email and one of our project engineers will be in touch.