Interview Questions

What is significance of using Volatile keyword?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

10. What is significance of using Volatile keyword?

Java allows threads to access shared variables. As a rule, to ensure that shared variables are consistently updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that enforces mutual exclusion for those shared variables.

If a field is declared volatile, in that case the Java memory model ensures that all threads see a consistent value for the variable.

Few small questions:
Q. Can we have volatile methods in java?
No, volatile is only a keyword, can be used only with variables.
Q. Can we have synchronized variable in java?
No, synchronized can be used only with methods, i.e. in method declaration.


DETAILED DESCRIPTION : Volatile keyword in java- difference between synchronized and volatile with programs, 10 key points about volatile keyword, why volatile variables are not cached in memory

(Continued on next question...)

Other Interview Questions