Sobes.tech
Junior — Middle

In which cases should the volatile keyword be used in Java?

sobes.tech AI

Answer from AI

The volatile keyword in Java is used for variables that are accessed by multiple threads simultaneously to guarantee visibility of changes to all threads. It prevents caching the variable's value in the thread's local memory and prohibits reordering operations on this variable.

Use volatile when:

  • A variable may be modified in one thread and read in another.
  • Atomicity of operations is not required (for example, incrementing is not suitable as it is not atomic).
  • You need to ensure the freshness of the value without using heavier synchronization mechanisms.

Example:

volatile boolean flag = false;

// Thread 1
flag = true;

// Thread 2
if (flag) {
    // will see the updated value
}

Without using volatile, Thread 2 may not see the update to flag due to caching.

In which cases should the volatile keyword be used in… - sobes.tech