Sobes.tech
Junior — Middle

Kas saaksite selgitada volatile märksõna eesmärki ja tööpõhimõtet Androidi arenduse kontekstis?

sobes.tech AI

Vastus AI-lt

The keyword volatile in Java (and, accordingly, in Android development) is used to ensure the visibility of changes to a variable across threads.

When a variable is declared as volatile, it guarantees that:

  • Reading the variable always occurs from the main memory, not from the thread's cache.
  • Writing to the variable immediately becomes visible to other threads.

This is important in multi-threaded Android environments to prevent situations where one thread changes the value, but another continues to see the old 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() might not see the change in isRunning and could enter an infinite loop.

However, volatile does not guarantee atomicity of complex operations; for that, other synchronization mechanisms are needed.