Junior — Middle
Can you explain the purpose and the working principle of the volatile keyword in the context of Android development?
sobes.tech AI
Answer from AI
The volatile keyword in Java (and consequently in Android development) is used to ensure the visibility of variable changes between threads.
When a variable is declared as volatile, it guarantees that:
- Reading the variable always occurs from main memory, not from the thread's cache.
- Writing to the variable immediately becomes visible to other threads.
This is important in a multi-threaded Android environment to avoid situations where one thread changes a value, but another continues to see the outdated value.
Example:
private volatile boolean isRunning = true;
public void stop() {
isRunning = false;
}
public void run() {
while (isRunning) {
// perform work
}
}
Without volatile, the thread executing run() may not see the change to isRunning and could loop infinitely.
However, volatile does not guarantee atomicity of complex operations; other synchronization mechanisms are needed for that.