Skip to content
Sharp

Concurrency basics · interview question

Consider the following code snippet. What issue might occur if 'flag' is not declared as 'volatile'?

Multiple choiceMediumchapter-15-curatedpremiumconcurrencythe-volatile-keyword
java
class Task implements Runnable {
  private boolean flag = false;
  public void run() {
    while (!flag) { /* do work */ }
  }
  public void stop() { flag = true; }
}
Choose one answer
Answer and explanation

Correct answer

C. The loop may never terminate

Why

Without 'volatile', changes to 'flag' may not be visible across threads, causing the loop to potentially run indefinitely.

Test yourself on Concurrency basics

A free test with instant, explained results. No account needed.

Start free test
All Concurrency basics questions →