Sobes.tech
Junior — Middle

What does the keyword volatile mean in programming languages like Java?

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.

Without volatile, one thread may see a stale value of the variable, as changes may remain in the local cache of another thread.

Example:

public class Counter {
    private volatile int count = 0;

    public void increment() {
        count++; // operation is not atomic, but volatile guarantees visibility
    }

    public int getCount() {
        return count;
    }
}

Important: volatile does not guarantee atomicity of operations, so for complex modifications, it is better to use synchronization or atomic classes from java.util.concurrent.atomic.

What does the keyword volatile mean in programming… - sobes.tech