Sobes.tech
Senior

What is volatile in Java, why is it needed, and how does it work?

sobes.tech AI

Answer from AI

In Java, the keyword volatile is used to denote a variable whose value may be changed by multiple threads simultaneously.

Why it's needed:

  • Ensures that reading and writing the variable happen directly from main memory, not from the CPU cache or registers.
  • Provides visibility of changes to the variable between threads without using heavier synchronization mechanisms.

How it works:

  • When writing to a volatile variable, the new value is immediately written to main memory.
  • When reading from a volatile variable, the thread always gets the current value from main memory.

Important: volatile does not guarantee atomicity of operations (for example, count++ is not atomic), only visibility of changes.

Example:

public class Example {
    private volatile boolean flag = false;

    public void writer() {
        flag = true; // writing to a volatile variable
    }

    public void reader() {
        if (flag) { // reading a volatile variable
            System.out.println("Flag is true");
        }
    }
}

In this example, if one thread calls writer(), and another calls reader(), the second thread is guaranteed to see the updated value of flag.

What is volatile in Java, why is it needed, and how… - sobes.tech