Sobes.tech
Junior — Middle

What is the role of the volatile keyword in Java and in what cases is its use justified?

sobes.tech AI

Answer from AI

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

Using volatile is justified when:

  • You need to ensure visibility of variable changes between threads.
  • There is no need for atomicity of complex operations (for example, increment is not atomic).

Example:

public class Flag {
  private volatile boolean active = true;

  public void stop() {
    active = false;
  }

  public void run() {
    while (active) {
      // perform work
    }
  }
}

Here, volatile guarantees that when one thread calls stop(), the other thread in the run() method will see the updated value of active and will exit the loop.

What is the role of the volatile keyword in Java and… - sobes.tech