Sobes.tech
Junior — Middle

What is the purpose of the volatile modifier in programming and what is its role?

sobes.tech AI

Answer from AI

The volatile modifier in Java is used to indicate that a variable's value may be changed at any time by other threads or hardware. It guarantees that when reading such a variable, the thread always gets the current value from main memory, not from the CPU cache.

The role of volatile is to ensure visibility of variable changes between threads without using full synchronization mechanisms (synchronized). However, volatile does not guarantee atomicity of operations, so for complex operations (e.g., increment), additional synchronization is required.

Example:

public class Example {
    private volatile boolean flag = false;

    public void setFlag() {
        flag = true; // change will be visible to other threads immediately
    }

    public void waitForFlag() {
        while (!flag) {
            // wait until flag becomes true
        }
        System.out.println("Flag set!");
    }
}