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
volatilevariable 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.
volatileprohibits reordering of writes to avolatilevariable with subsequent accesses to other variables, and reads from avolatilevariable with previous accesses to other variables. - Does not guarantee atomicity:
volatileprovides visibility but does not guarantee that compound operations (e.g., incrementi++, which consists of read, modify, and write) are atomic. For atomic operations on primitive types, classes from thejava.util.concurrent.atomicpackage 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
}