Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

The volatile keyword in Java is used to indicate that a variable's value may be changed by multiple threads simultaneously. It guarantees that reads and writes to this variable will happen directly from main memory, not from the thread's cache, ensuring visibility of changes across threads.

Use volatile in cases where:

  • A variable may be modified in one thread and read in another.
  • Atomicity of complex operations (e.g., increment) is not required, only the current value's relevance.
  • It is necessary to avoid using heavier synchronization mechanisms (e.g., synchronized) when just visibility of changes is sufficient.

Example:

class Flag {
    private volatile boolean stop = false;

    public void requestStop() {
        stop = true;
    }

    public void run() {
        while (!stop) {
            // work
        }
    }
}

Here, without volatile, the thread executing run() might not see the change to stop.

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