Grokking Java Interview Questions
Vote

0% completed

​

The Java Memory Model and volatile

One thread runs the loop while (!stop) n++;, and one second later another thread executes stop = true. When does the loop end?

With an ordinary static boolean, it may never end. We ran this program three times on Java 21, waited five more seconds after the assignment, and each time the loop was still running. After the word volatile was added to the field, the loop ended in all three runs.

The four questions of this lesson explain why the first version fails, what volatile changes, which rules decide what one thread sees of another, and where volatile is too weak or required.

.....

.....

.....

Like the course? Get enrolled and start learning!

Reading Progress

0%


Vote for new content