Sobes.tech
Junior — Middle

What is the purpose of the keyword volatile in the programming language?

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. This helps prevent issues related to caching and compiler optimizations that could lead to incorrect behavior in a multithreaded environment.

Example:

private volatile boolean running = true;

public void stop() {
    running = false; // change will be visible to other threads
}

public void run() {
    while (running) {
        // perform task
    }
}
What is the purpose of the keyword volatile in the… - sobes.tech