Sobes.tech
Senior

What is volatile?

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. 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.

This means that if one thread changes the value of a volatile variable, other threads will immediately see this new value.

Example:

public class Example {
    private volatile boolean flag = false;

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

    public void reader() {
        if (flag) {
            // will definitely see the updated value of flag
        }
    }
}

It is important to understand that volatile does not guarantee atomicity of operations, only visibility of changes. For complex operations, synchronization or other concurrency control mechanisms are necessary.