Volatile Interview Questions :-

  What is Volatile keyword in Java?

Volatile is a declaration that a variable can be accessed by multiple threads and hence shouldn't be cached.

  When to use volatile variable in Java?

Volatile keyword is used with only variable in Java and it guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache. So we can use volatile to achieve synchronization because its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values.

Volatile modifier also helps to prevent reordering of code by compiler and offer visibility guarantee by happens-before relationship.

  How does volatile affect code optimization by compiler?

Volatile is an instruction that the variables can be accessed by multiple threads and hence shouldn't be cached. As volatile variables are never cached and hence their retrieval cannot be optimized.

  What is the difference between transient and volatile variable in Java?

Transient variable :-

  What is an Immutable Object ?

Object that can't be changed after instantiation.


PHP is a server-side scripting language designed primarily for web development but is also used as a general-purpose programming language..

Read more