The volatile keyword

1 AM November 24, 2004

Java’s execution order model gives me headaches when I think about the details, but it boils down to this:

There is no guarantee that two threads will have a consistent view of any given variable, unless (a) the threads synchronize on the same some object at some stage, or (b) the variable is declared volatile.

Using volatile forces the thread to retrieve the value from main memory before it is read, and to set it immediately after it is written, ensuring that

I find volatile handy where one thread is writing a variable, multiple threads may read the variable and there is no need for threads to block on the variable. For example:

static volatile int progress = 0;

static void doIt() throws InterruptedException {

(new Thread() {

public void run() {

try {

while (progress < 100) {




} catch (InterruptedException e) {




while (progress < 100) {






This snippet of code starts a thread that increments the progress variable, while the main thread waits for the variable to reach 100. Since the variable is declared volatile, the watching thread is guaranteed to see the same value that the incrementing thread sees. If progress was not volatile, the watching thread may not ever see the value change – even after the incrementing thread had terminated.

Update: Any use of synchronize causes a thread to make any outstanding writes to main memory, and to re-read variable values from memory before using them again.

By alang | # | Comments (1)
(Posted to javablogs and Java)


At 08:53, 24 Nov 2004 Tom Hawtin wrote:

Note ++ is not atomic so two threads each incrementing a volatile may only increment it by one. If you only have one writing thread (other than initialisation), then that isn't a problem. In your example the volatile may be shared between multiple invocations of doIt.


Add Comment

(Not displayed)

(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)

© 2003-2006 Alan Green