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
class Task implements Runnable {
private boolean flag = false;
public void run() {
while (!flag) { /* do work */ }
}
public void stop() { flag = true; }
}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.
More Concurrency basics questions
- How can you avoid deadlocks when using multiple ReentrantLocks in a method?
- What does the 'volatile' keyword guarantee in Java?
- Why might using 'volatile' alone be insufficient for ensuring thread safety when updating a shared counter?
- When using synchronized blocks, how can you ensure fairness among threads?
- How would you explain a common use case for 'volatile' variables in an interview?
- How can you ensure that a thread releases a lock if it was not able to acquire it using tryLock()?