Sobes.tech
Middle

Что произойдет, если применить ключевое слово volatile к переменной в Java?

sobes.tech AI

Answer from AI

volatile guarantees visibility of variable updates to all threads.

Applying volatile to a variable:

  • Guarantees visibility: Writing to a volatile variable by one thread becomes visible to all other threads that subsequently read this variable.
  • Prohibits reordering: JVM and processors may reorder instructions for performance optimization. volatile prohibits reordering of writes to a volatile variable with subsequent accesses to other variables, and reads from a volatile variable with previous accesses to other variables.
  • Does not guarantee atomicity: volatile provides visibility but does not guarantee that compound operations (e.g., increment i++, which consists of read, modify, and write) are atomic. For atomic operations on primitive types, classes from the java.util.concurrent.atomic package are often used.

Example usage:

// Variable for thread stop flag
private volatile boolean stopped = false;

public void run() {
    while (!stopped) {
        // Perform work
    }
}

public void stop() {
    stopped = true; // Change the flag, visible to other threads
}
Что произойдет, если применить ключевое слово… - sobes.tech